import { action, observable, toJS } from "mobx";
import API from '../../../apis/task';
import CellType from '../../excel/celltypes';
import ExcelAPI from '../../../apis/excel';
import TaskAPI from '../../../apis/task';
import FunAPI from '../../../apis/formula';
import getCellName from '../../../utils/getCellName';
import { Tools } from 'weaver-mobile';
import { each } from 'lodash';
//import { message } from 'antd-mobile';
import { Toast as message } from 'weaver-mobile';
import route from "../../../constants/route";
import { register, removeAllSpan, sortRecords } from "./command";
import MenuActions from './event/menu/action';
import * as Events from './event';
import CustomFunction from "./event/function";
import Excel from "./code/plugin";
import {isMobile} from "../../../utils/mobileDetect";
import jQuery from 'jquery';
import { Base64 } from 'js-base64';
const getLabel = Tools.getLabel;
export const styleNames = ["backColor", "foreColor", "hAlign", "vAlign",
    "font", "formatter", "borderLeft", "borderTop", "borderRight",
    "borderBottom", "diagonalDown", "diagonalUp", "locked", "textIndent",
    "wordWrap", "shrinkToFit", "backgroundImage", "backgroundImageLayout",
    "tabStop", "textDecoration", "imeMode", "watermark", "cellPadding",
    "labelOptions", "quotePrefix", "isVerticalText"];

export default class TaskViewExcelStore {
    @observable title = '';
    @observable activeCellName = '';
    @observable isInit = false;
    @observable loading = false;
    @observable showDetailDelete = false;
    @observable customFuns;
    @observable oldPage;
    @observable excelStore;
    @observable uploadtitle = getLabel('502835', '导入数据');
    @observable visible = false;
    @observable pageid = '';
    @observable needCheck = true;
    deletedRows = {};
    func = [];

    @observable loadingPage = true;
    @observable isRight;
    @observable cuscode = '';
    @observable rowControl = {};
    @observable autoSaveDatas = [];
    @observable firstSet = false;
    @observable autoSaveDatasvisible = false;
    @observable canSubmit = false;
    @observable requiredCellBoderStyle = {};
    @observable requiredCellName = "";
    @observable fieldAssignList = [];
    @observable isAssign = true;//其他cell.value操作时是否执行数据源赋值逻辑
    @observable detailFields = [];//取excel表格中的所有子表字段
    @observable mainFields = [];//取excel表格中的所有主表字段
    customBindingCurrentT = {};
    customExpandFieldname = {}; // 一对多的字段，bindingPath需要单独设置
    customExpandCurrent = {};//扩展字段编号维护
    @observable otherrightExpandMap = {};
    @observable pgvisible = false;
    @observable uploadName;
    @observable progress = 0;
    @observable autoFitSheetMap = {};
    @observable uploadPids = [];
    @observable changeFieldList = [];
    @observable timer = {};
    @observable detailFieldInfoMap = {}
    @observable mainFieldInfoMap = {}
    tableFirstRowHeight = {};
    @observable ismobile = isMobile();
    constructor() {
        each(MenuActions, (value, key) => {
            this[key] = action(value.bind(this));
        });
        each(Events, (value, key) => {
            this[key] = action(value.bind(this));
        });
    }
    refresh = () => {
        setTimeout(() => {
            this.workbook.refresh();
        }, 10);
    }
    @action loadWorkbook = () => {
        this.isInit = true;
    }
    @action initWorkbook = (workbook, readonly) => {
        this.workbook = workbook;
        window.workbookInstance = workbook;
        this.readonly = readonly;
    }
    @action init = (params) => {
        this.func = [];
        this.params = params;
        this.pageid = params.pageid;

        if (this.intervalAutoSave) {
            clearInterval(this.intervalAutoSave);
        }
        this.loading = true;
        API.showDetail(this.params).then(({ isShowDetail,rightLevel }) => {
            this.loadingPage = false;
            // (!rightLevel || (rightLevel && rightLevel == 2))
            if (isShowDetail && (rightLevel ==1 || rightLevel == 2) ) {
                this.isRight = rightLevel == 2;
                Promise.all([
                    API.getExcelPageBaseInfo(this.params),
                    API.getExcelPageDataSource(this.params),
                    API.getExcelPageUserInfo(this.params),
                    FunAPI.loadFormula(this.params.pageid)
                ]).then(([json, dataSource, defaultInfoMap, formulas]) => {
                    // 避免多语言被转换，加了这层base64加密解密
                    json = JSON.parse(Base64.fromBase64(json));
                    this.customFuns = formulas;
                    const { showDefault, hasData } = dataSource;
                    this.showDefault = showDefault;
                    this.hasData = hasData;
                    this.userInfoMap = defaultInfoMap.userInfoMap;
                    this.defaultValueMap = defaultInfoMap.defaultValueMap;
                    this.commonDefault = defaultInfoMap.commonDefault;
                    this.beforeNodeDefault = defaultInfoMap.beforeNodeDefault;
                    this.autoFitSheetMap = json.sheetsetting ? JSON.parse(json.sheetsetting) : {};
                    delete dataSource.showDefault;
                    delete dataSource.hasData;
                    this.setViewInfo({ page: { json, dataSource } });

                })
                API.getExcelPageFieldAssign(this.params).then(assignList => {
                    this.fieldAssignList = assignList;
                });
                API.getExcelPageDetailProps(this.params).then(props => {
                    this.rowControl = props;
                });
                API.getExcelPageAutoSaveInfo(this.params).then(viewPage => {
                    // 有自动保存设置、且可编辑
                    const { autoSaveType } = viewPage;
                    if (autoSaveType == '1' && this.canSubmit && this.notAutoSave != '1') {
                        this.autoSaveDatas = viewPage.autoSaveDatas || [];
                        if (viewPage.autoSaveDatas && !this.firstSet) {
                            this.firstSet = true;
                            this.autoSaveDatasvisible = true;
                        }
                        this.autoSave(viewPage);
                    }
                });

                //API.excel(this.params).then(this.setViewInfo);
            } else {
                this.isRight = false;
            }
        })
        /*  API.showDetail({ nodeid: this.params.nodeid, pageid: this.params.pageid }).then(result => { //
             this.loadingPage = false;
             if (result.isShowDetail) {
                 this.isRight = true;
                 Promise.all([
                     API.excel(this.params),
                     FunAPI.loadFormula(this.params.pageid)
                 ]).then(([page, formulas]) => {
 
                     this.customFuns = formulas;
                     this.setViewInfo(page);
                 })
                 //API.excel(this.params).then(this.setViewInfo);
             }
         }); */
    }

    @action setViewInfo = (view) => {
        const { page = {} } = view || {};
        this.title = (page.json || {}).pagename;
        //this.canSubmit = view.canSubmit;
        this.loading = false;
        this.showPage(page);

    }

    // 初始化后触发下拉框制约；以及设置用户自带默认值
    @action
    changeSelectTypeValue = () => {
        this.workbook.suspendPaint();
        this.isAssign = false;
        const activeIndex = this.workbook.getActiveSheetIndex();
        this.workbook.sheets.forEach((sheet, index) => {
            if(this.workbook.getSheet(index).visible()){
                this.workbook.getTab().KD(index);
            }
        })
        this.workbook.setActiveSheetIndex(activeIndex);
        this.workbook.sheets.forEach(sheet => {
            const sheetname = sheet.name();
            // 明细表
            sheet.tables.all().forEach(table => {
                const bindingPath = table.bindingPath();
                const tablename = table.name();
                if (bindingPath) {
                    const { col, colCount, row, rowCount } = table.dataRange();
                    for (let i = 0; i < colCount; i++) {
                        const cell = sheet.getCell(Number(row), Number(col + i));
                        const cellType = cell.cellType();
                        if (cellType && cellType.typeName == 'WeaSelectCellType' && cellType.fieldType) {
                            for (let j = 0; j < rowCount; j++) {
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                    c.value('-999');
                                    c.value(value);
                                } else {
                                    c.value('-999');
                                    c.value(value);
                                }
                            }

                        }
                        if (this.initstatus && cellType && cellType.fieldType) {
                         
                            const fieldname = table.getColumnDataField(i);
                        if(this.beforeNodeDefault && this.defaultValueMap && this.defaultValueMap[sheetname] && this.defaultValueMap[sheetname][tablename] && this.defaultValueMap[sheetname][tablename][fieldname]!== undefined) {
                            
                            // 节点前赋值
                            const valueMap = this.defaultValueMap[sheetname][tablename];
                            const defaultValue = valueMap[fieldname];
                            if(fieldname && defaultValue) {
                                for (let j = 0; j < rowCount; j++) {
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value(defaultValue);
                                    }
                                }
                            }
                            
                        } else {
                            // 默认类型赋值
                            
                            //WeaDatePickerCellType

                            //WeaTimePickerCellType

                            //WeaBrowserCellType
                            if (cellType.typeName == 'WeaDatePickerCellType') {
                                if (cellType.browserType == '2') {
                                    const data = this.getcurrentTime(2);
                                    for (let j = 0; j < rowCount; j++) {
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value(data);
                                        }
                                    }
                                } else if (cellType.browserType == '290') {
                                    const data = this.getcurrentTime(4);
                                    for (let j = 0; j < rowCount; j++) {
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value(data);
                                        }
                                    }
                                }
                            } else if (cellType.typeName == 'WeaTimePickerCellType') {
                                const data = this.getcurrentTime(3);
                                for (let j = 0; j < rowCount; j++) {
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value(data);
                                    }
                                }
                            } else if (cellType.typeName == 'WeaBrowserCellType') {
                                // 人力资源
                                if (this.userInfoMap.hrm && (cellType.browserType == '1' || cellType.browserType == '17')) {
                                    const data = this.userInfoMap.hrm;
                                    for (let j = 0; j < rowCount; j++) {
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value([data]);
                                        }
                                    }
                                } else if (this.userInfoMap.com && (cellType.browserType == '164' || cellType.browserType == '194')) {
                                    // 分部
                                    const data = this.userInfoMap.com;
                                    for (let j = 0; j < rowCount; j++) {
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value([data]);
                                        }
                                    }
                                } else if (this.userInfoMap.dept && (cellType.browserType == '4' || cellType.browserType == '57')) {
                                    // 部门
                                    const data = this.userInfoMap.dept;
                                    for (let j = 0; j < rowCount; j++) {
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value([data]);
                                        }
                                    }
                                } else if (this.userInfoMap.jobs && (cellType.browserType == '24' || cellType.browserType == '278')) {
                                    // 岗位
                                    const data = this.userInfoMap.jobs;
                                    for (let j = 0; j < rowCount; j++) {
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value([data]);
                                        }
                                    }
                                } else if (cellType.browserType == "178") {
                                    const data = this.getcurrentTime(1);
                                    for (let j = 0; j < rowCount; j++) {
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value([{ id: data, name: data }]);
                                        }
                                    }
                                }
                            }

                        }
                           
                    }
                        
                    }
                } else if(tablename.startsWith('custom')) {
                    // 自定义明细表
                    const { col, colCount, row, rowCount } = table.dataRange();
                    for (let i = 0; i < colCount; i++) {
                        for(let j = 0 ; j <rowCount ; j++) {
                            const cell = sheet.getCell(Number(row + j), Number(col + i));
                            const cellType = cell.cellType();
                            const bPath = cell.bindingPath();
                            if (cellType && cellType.typeName == 'WeaSelectCellType' && cellType.fieldType) {
                                const value = cell.value();
                                if (value) {
                                    cell.value('-999');
                                    cell.value(value);
                                } else {
                                    cell.value('-999');
                                    cell.value(value);
                                }
    
                            }
                            if (this.initstatus && bPath && cellType && cellType.fieldType) {
                             
                                const fieldname = this.getFieldName(bPath);
                            if(this.beforeNodeDefault && this.defaultValueMap && this.defaultValueMap[sheetname] && this.defaultValueMap[sheetname][tablename] && this.defaultValueMap[sheetname][tablename][fieldname]!== undefined) {
                                
                                // 节点前赋值
                                const valueMap = this.defaultValueMap[sheetname][tablename];
                                const defaultValue = valueMap[fieldname];
                                if(fieldname && defaultValue) {
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value(defaultValue);
                                    }
                                }
                                
                            } else {
                                // 默认类型赋值
                                
                                //WeaDatePickerCellType
    
                                //WeaTimePickerCellType
    
                                //WeaBrowserCellType
                                if (cellType.typeName == 'WeaDatePickerCellType') {
                                    if (cellType.browserType == '2') {
                                        const data = this.getcurrentTime(2);
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value(data);
                                        }
                                    } else if (cellType.browserType == '290') {
                                        const data = this.getcurrentTime(4);
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value(data);
                                        }
                                    }
                                } else if (cellType.typeName == 'WeaTimePickerCellType') {
                                    const data = this.getcurrentTime(3);
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value(data);
                                    }
                                    
                                } else if (cellType.typeName == 'WeaBrowserCellType') {
                                    // 人力资源
                                    if (this.userInfoMap.hrm && (cellType.browserType == '1' || cellType.browserType == '17')) {
                                        const data = this.userInfoMap.hrm;
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value([data]);
                                        }
                                        
                                    } else if (this.userInfoMap.com && (cellType.browserType == '164' || cellType.browserType == '194')) {
                                        // 分部
                                        const data = this.userInfoMap.com;
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value([data]);
                                        }
                                        
                                    } else if (this.userInfoMap.dept && (cellType.browserType == '4' || cellType.browserType == '57')) {
                                        // 部门
                                        const data = this.userInfoMap.dept;
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value([data]);
                                        }
                                        
                                    } else if (this.userInfoMap.jobs && (cellType.browserType == '24' || cellType.browserType == '278')) {
                                        // 岗位
                                        const data = this.userInfoMap.jobs;
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value([data]);
                                        }
                                        
                                    } else if (cellType.browserType == "178") {
                                        const data = this.getcurrentTime(1);
                                        const c = sheet.getCell(Number(row + j), Number(col + i));
                                        const value = c.value();
                                        if (value) {
                                        } else {
                                            c.value([{ id: data, name: data }]);
                                        }
                                        
                                    }
                                }
    
                            }
                               
                        }
                    }
                        
                        
                    }
                }

            });

            const { data } = sheet.toJSON();
            if (data) {
                const { dataTable } = data;
                if (dataTable) {
                    each(dataTable, (o, rowIndex) => {
                        each(o, (obj, colIndex) => {
                            const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
                            if (bindingPath && bindingPath.indexOf('.custom_') == -1) {
                                const cell = sheet.getCell(Number(rowIndex), Number(colIndex));
                                const cellType = cell.cellType();
                                if (cellType && cellType.typeName == 'WeaSelectCellType' && cellType.fieldType) {
                                    const value = cell.value();
                                    if (value) {
                                        cell.value('-999');
                                        cell.value(value);
                                    } else {
                                        cell.value('-999');
                                        cell.value(value);
                                    }
                                }
                                if (this.initstatus && cellType && cellType.fieldType) {
                                    const fieldname = this.getMainFieldName(cell.bindingPath());
                                    // 特定字段类型赋值
                                    if(this.beforeNodeDefault && this.defaultValueMap && this.defaultValueMap[sheetname] && this.defaultValueMap[sheetname][fieldname]!== undefined) {
                                        // 节点前赋值
                                        const valueMap = this.defaultValueMap[sheetname];
                                        const defaultValue = valueMap[fieldname];
                                        if(fieldname && defaultValue) {
                                            const value = cell.value();
                                            if (value) {
                                            } else {
                                                cell.value(defaultValue);
                                            }
                                            
                                        }
                                        
                                    } else {
                                        if (cellType.typeName == 'WeaDatePickerCellType') {
                                            if (cellType.browserType == '2') {
                                                const data = this.getcurrentTime(2);
                                                const value = cell.value();
                                                if (value) {
                                                } else {
                                                    cell.value(data);
                                                }
                                            } else if (cellType.browserType == '290') {
                                                const data = this.getcurrentTime(4);
                                                const value = cell.value();
                                                if (value) {
                                                } else {
                                                    cell.value(data);
                                                }
                                            }
                                        } else if (cellType.typeName == 'WeaTimePickerCellType') {
                                            const data = this.getcurrentTime(3);
                                            const value = cell.value();
                                            if (value) {
                                            } else {
    
                                                cell.value(data);
                                            }
                                        } else if (cellType.typeName == 'WeaBrowserCellType') {
    
                                            // 人力资源
                                            if (this.userInfoMap.hrm && (cellType.browserType == '1' || cellType.browserType == '17')) {
    
    
                                                const data = this.userInfoMap.hrm;
                                                const value = cell.value();
                                                if (value) {
                                                } else {
                                                    cell.value([data]);
                                                }
    
                                            } else if (this.userInfoMap.com && (cellType.browserType == '164' || cellType.browserType == '194')) {
                                                // 分部
                                                const data = this.userInfoMap.com;
                                                const value = cell.value();
                                                if (value) {
                                                } else {
                                                    cell.value([data]);
                                                }
                                            } else if (this.userInfoMap.dept && (cellType.browserType == '4' || cellType.browserType == '57')) {
                                                // 部门
                                                const data = this.userInfoMap.dept;
                                                const value = cell.value();
                                                if (value) {
                                                } else {
                                                    cell.value([data]);
                                                }
                                            } else if (this.userInfoMap.jobs && (cellType.browserType == '24' || cellType.browserType == '278')) {
                                                // 岗位
                                                const data = this.userInfoMap.jobs;
                                                const value = cell.value();
                                                if (value) {
                                                } else {
                                                    cell.value([data]);
                                                }
                                            } else if (cellType.browserType == "178") {
                                                const data = this.getcurrentTime(1);
                                                const value = cell.value();
                                                if (value) {
                                                } else {
                                                    cell.value([{ id: data, name: data }]);
                                                }
                                            }
                                        }
                                    }
                                    
                                }
                            }

                        });
                    });

                }
            }
        });
        this.isAssign = true;
        this.workbook.resumePaint();
    }

    getMainFieldName = (path) => {
        const strs = path.split(".");
        return strs[strs.length-1]
    }

    // 针对有时候span不生效的情况
    @action
    resetTableSpan = (table) => {
        this.workbook.suspendPaint();
        const sheet = this.workbook.getActiveSheet();
        const {row, col, rowCount, colCount} = table.dataRange();
        for(let r = row ; r < rowCount + row; r++) {

            for(let c = col; c < col + colCount; c++) {
                const span = sheet.getSpan(r, c);
                if(span && r == span.row && c == span.col) {
                    sheet.addSpan(span.row, span.col, span.rowCount, span.colCount)
                }
            }
        }
        this.workbook.resumePaint();
    }

    // 当前sheet页新增列后触发
    @action
    setUserinfo2newCol = (table, col, selectionColCount) => {
        this.workbook.suspendPaint();
        const sheet = this.workbook.getActiveSheet();
        const sheetname = sheet.name();
        const tablename = table.name();

        if(tablename.startsWith('custom')) {
            
            console.log(tablename,"tablename");
                // 自定义明细表
                const { row, rowCount } = table.dataRange();
                for (let i = 0; i < selectionColCount; i++) {
                    for(let j = 0 ; j < rowCount ; j++) {
                        const cell = sheet.getCell(Number(row + j), Number(col + i));
                        const cellType = cell.cellType();
                        const bPath = cell.bindingPath();
                        if (cellType && cellType.typeName == 'WeaSelectCellType' && cellType.fieldType) {
                            const value = cell.value();
                            if (value) {
                                cell.value('-999');
                                cell.value(value);
                            } else {
                                cell.value('-999');
                                cell.value(value);
                            }
    
                        }
                        if (bPath && cellType && cellType.fieldType) {
                         
                            const fieldname = this.getFieldName(bPath);
                        if(this.beforeNodeDefault && this.defaultValueMap && this.defaultValueMap[sheetname] && this.defaultValueMap[sheetname][tablename] && this.defaultValueMap[sheetname][tablename][fieldname]!== undefined) {
                            
                            // 节点前赋值
                            const valueMap = this.defaultValueMap[sheetname][tablename];
                            const defaultValue = valueMap[fieldname];
                            if(fieldname && defaultValue) {
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value(defaultValue);
                                }
                            }
                            
                        } else {
                            // 默认类型赋值
                            
                            //WeaDatePickerCellType
    
                            //WeaTimePickerCellType
    
                            //WeaBrowserCellType
                            if (cellType.typeName == 'WeaDatePickerCellType') {
                                if (cellType.browserType == '2') {
                                    const data = this.getcurrentTime(2);
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value(data);
                                    }
                                } else if (cellType.browserType == '290') {
                                    const data = this.getcurrentTime(4);
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value(data);
                                    }
                                }
                            } else if (cellType.typeName == 'WeaTimePickerCellType') {
                                const data = this.getcurrentTime(3);
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value(data);
                                }
                                
                            } else if (cellType.typeName == 'WeaBrowserCellType') {
                                // 人力资源
                                if (this.userInfoMap.hrm && (cellType.browserType == '1' || cellType.browserType == '17')) {
                                    const data = this.userInfoMap.hrm;
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value([data]);
                                    }
                                    
                                } else if (this.userInfoMap.com && (cellType.browserType == '164' || cellType.browserType == '194')) {
                                    // 分部
                                    const data = this.userInfoMap.com;
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value([data]);
                                    }
                                    
                                } else if (this.userInfoMap.dept && (cellType.browserType == '4' || cellType.browserType == '57')) {
                                    // 部门
                                    const data = this.userInfoMap.dept;
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value([data]);
                                    }
                                    
                                } else if (this.userInfoMap.jobs && (cellType.browserType == '24' || cellType.browserType == '278')) {
                                    // 岗位
                                    const data = this.userInfoMap.jobs;
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value([data]);
                                    }
                                    
                                } else if (cellType.browserType == "178") {
                                    const data = this.getcurrentTime(1);
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value([{ id: data, name: data }]);
                                    }
                                    
                                }
                            }
    
                        }
                           
                    }
                }
                    
                    
                }
            }
            this.workbook.resumePaint();
    }

    // 当前sheet页新增行后触发
    @action
    setUserinfo2newRow = (table, row, selectionRowCount) => {
        this.workbook.suspendPaint();
        const sheet = this.workbook.getActiveSheet();
        const sheetname = sheet.name();
        const bindingPath = table.bindingPath();
        const tablename = table.name();
        if (bindingPath) {
            const { col, colCount, row: startRow, rowCount: count } = table.dataRange();
            if (count + startRow < row + selectionRowCount) {
                selectionRowCount = count + startRow - row;
            }
            const rowCount = selectionRowCount;

            for (let i = 0; i < colCount; i++) {
                const cell = sheet.getCell(Number(row), Number(col + i));
                const cellType = cell.cellType();

                if (cellType && cellType.typeName == 'WeaSelectCellType' && cellType.fieldType) {
                    for (let j = 0; j < count; j++) {
                        const c = sheet.getCell(Number(startRow + j), Number(col + i));
                        const value = c.value();
                        if (value) {

                            c.value('-999');
                            c.value(value);
                        } else {
                            c.value('-999');
                            c.value(value);
                        }
                    }

                    // #676394 概述：【正式】【E9补丁包1908】解决了默认显示字段属性为只读时，不显示默认值的问题 去掉  && cellType.viewAttr != 1
                } 
                
                if (cellType && cellType.fieldType) {
                    //WeaDatePickerCellType

                    //WeaTimePickerCellType

                    //WeaBrowserCellType
                    
                    const fieldname = table.getColumnDataField(i);
                    if(this.beforeNodeDefault && this.defaultValueMap && this.defaultValueMap[sheetname] && this.defaultValueMap[sheetname][tablename] && this.defaultValueMap[sheetname][tablename][fieldname]!== undefined) {
                        const valueMap = this.defaultValueMap[sheetname][tablename];
                        const defaultValue = valueMap[fieldname];
                        if(fieldname && defaultValue) {
                            for (let j = 0; j < rowCount; j++) {
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value(defaultValue);
                                }
                            }
                        }
                    } else {
                        // 特定类型赋值
                        if (cellType.typeName == 'WeaDatePickerCellType') {

                            if (cellType.browserType == '2') {
                                const data = this.getcurrentTime(2);
                                for (let j = 0; j < rowCount; j++) {
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value(data);
                                    }
                                }
                            } else if (cellType.browserType == '290') {
                                const data = this.getcurrentTime(4);
                                for (let j = 0; j < rowCount; j++) {
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value(data);
                                    }
                                }
                            }
                        } else if (cellType.typeName == 'WeaTimePickerCellType') {
                            const data = this.getcurrentTime(3);
                            for (let j = 0; j < rowCount; j++) {
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value(data);
                                }
                            }
                        } else if (cellType.typeName == 'WeaBrowserCellType') {
    
                            // 人力资源
                            if (this.userInfoMap.hrm && (cellType.browserType == '1' || cellType.browserType == '17')) {
                                const data = this.userInfoMap.hrm;
                                for (let j = 0; j < rowCount; j++) {
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value([data]);
                                    }
                                }
    
                            } else if (this.userInfoMap.com && (cellType.browserType == '164' || cellType.browserType == '194')) {
                                // 分部
                                const data = this.userInfoMap.com;
                                for (let j = 0; j < rowCount; j++) {
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value([data]);
                                    }
                                }
                            } else if (this.userInfoMap.dept && (cellType.browserType == '4' || cellType.browserType == '57')) {
                                // 部门
                                const data = this.userInfoMap.dept;
                                for (let j = 0; j < rowCount; j++) {
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value([data]);
                                    }
                                }
                            } else if (this.userInfoMap.jobs && (cellType.browserType == '24' || cellType.browserType == '278')) {
                                // 岗位
                                const data = this.userInfoMap.jobs;
                                for (let j = 0; j < rowCount; j++) {
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value([data]);
                                    }
                                }
                            } else if (cellType.browserType == "178") {
                                const data = this.getcurrentTime(1);
                                for (let j = 0; j < rowCount; j++) {
                                    const c = sheet.getCell(Number(row + j), Number(col + i));
                                    const value = c.value();
                                    if (value) {
                                    } else {
                                        c.value([{ id: data, name: data }]);
                                    }
                                }
                            }
                        }
                    }

                }
            }
        } else if(tablename.startsWith('custom')) {
            
        console.log(tablename,"tablename");
            // 自定义明细表
            const { col, colCount } = table.dataRange();
            for (let i = 0; i < colCount; i++) {
                for(let j = 0 ; j < selectionRowCount ; j++) {
                    const cell = sheet.getCell(Number(row + j), Number(col + i));
                    const cellType = cell.cellType();
                    const bPath = cell.bindingPath();
                    if (cellType && cellType.typeName == 'WeaSelectCellType' && cellType.fieldType) {
                        const value = cell.value();
                        if (value) {
                            cell.value('-999');
                            cell.value(value);
                        } else {
                            cell.value('-999');
                            cell.value(value);
                        }

                    }
                    if (bPath && cellType && cellType.fieldType) {
                     
                        const fieldname = this.getFieldName(bPath);
                    if(this.beforeNodeDefault && this.defaultValueMap && this.defaultValueMap[sheetname] && this.defaultValueMap[sheetname][tablename] && this.defaultValueMap[sheetname][tablename][fieldname]!== undefined) {
                        
                        // 节点前赋值
                        const valueMap = this.defaultValueMap[sheetname][tablename];
                        const defaultValue = valueMap[fieldname];
                        if(fieldname && defaultValue) {
                            const c = sheet.getCell(Number(row + j), Number(col + i));
                            const value = c.value();
                            if (value) {
                            } else {
                                c.value(defaultValue);
                            }
                        }
                        
                    } else {
                        // 默认类型赋值
                        
                        //WeaDatePickerCellType

                        //WeaTimePickerCellType

                        //WeaBrowserCellType
                        if (cellType.typeName == 'WeaDatePickerCellType') {
                            if (cellType.browserType == '2') {
                                const data = this.getcurrentTime(2);
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value(data);
                                }
                            } else if (cellType.browserType == '290') {
                                const data = this.getcurrentTime(4);
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value(data);
                                }
                            }
                        } else if (cellType.typeName == 'WeaTimePickerCellType') {
                            const data = this.getcurrentTime(3);
                            const c = sheet.getCell(Number(row + j), Number(col + i));
                            const value = c.value();
                            if (value) {
                            } else {
                                c.value(data);
                            }
                            
                        } else if (cellType.typeName == 'WeaBrowserCellType') {
                            // 人力资源
                            if (this.userInfoMap.hrm && (cellType.browserType == '1' || cellType.browserType == '17')) {
                                const data = this.userInfoMap.hrm;
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value([data]);
                                }
                                
                            } else if (this.userInfoMap.com && (cellType.browserType == '164' || cellType.browserType == '194')) {
                                // 分部
                                const data = this.userInfoMap.com;
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value([data]);
                                }
                                
                            } else if (this.userInfoMap.dept && (cellType.browserType == '4' || cellType.browserType == '57')) {
                                // 部门
                                const data = this.userInfoMap.dept;
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value([data]);
                                }
                                
                            } else if (this.userInfoMap.jobs && (cellType.browserType == '24' || cellType.browserType == '278')) {
                                // 岗位
                                const data = this.userInfoMap.jobs;
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value([data]);
                                }
                                
                            } else if (cellType.browserType == "178") {
                                const data = this.getcurrentTime(1);
                                const c = sheet.getCell(Number(row + j), Number(col + i));
                                const value = c.value();
                                if (value) {
                                } else {
                                    c.value([{ id: data, name: data }]);
                                }
                                
                            }
                        }

                    }
                       
                }
            }
                
                
            }
        }
        this.workbook.resumePaint();
    }

    // 获取日期时间 type 1：年份；2：日期；3：时间；4：日期时间
    getcurrentTime = (type) => {
        const now = new Date();

        const year = now.getFullYear();       //年
        const month = now.getMonth() + 1;     //月
        const day = now.getDate();            //日

        const hh = now.getHours();            //时
        const mm = now.getMinutes();          //分
        const ss = now.getSeconds();


        let ymd = year + "-";
        let time = "";

        if (month < 10)
            ymd += "0";

        ymd += month + "-";

        if (day < 10)
            ymd += "0";

        ymd += day;

        if (hh < 10)
            time += "0";

        time += hh + ":";
        if (mm < 10)
            time += '0';
        time += mm;

        if (type == 1) {
            return year + "";
        } else if (type == 2) {
            return ymd;
        } else if (type == 3) {
            return time;
        } else if (type == 4) {
            return ymd + " " + time;
        }
    }

    autoSave = (view) => {
        const { autoSaveType, saveTime = 0, saveTimeType = 0 } = view || {};

        let intervalTime = 0;
        if (saveTime > 0) {
            if (saveTimeType == 0) {
                intervalTime = saveTime * 60 * 1000;
            } else {
                intervalTime = saveTime * 60 * 60 * 1000;
            }
            this.intervalAutoSave = setInterval(() => {
                this.autoSaveData();
            }, intervalTime)

        }
    }

    autoSaveData = () => {
        if (!this.doBefore()) {
            return;

        }
        const source = this.dataSourceInstance.getSource();
        let wbook = null;
        if(this.hasCustomTable) {
            wbook = this.workbook;
        }
        TaskAPI.autoSaveData({
            ...this.params,
            datas: JSON.stringify(source),
            wbook:wbook ? JSON.stringify(wbook) : null,
            deletedRows: JSON.stringify(this.deletedRows),
        }).then((ds) => {
            if (ds) {
                this.autoSaveDatas = ds;
                if (!this.firstSet) {
                    this.firstSet = true;
                    this.autoSaveDatasvisible = true;
                }

                message.success(getLabel('508530', '自动') + getLabel('502231', '保存成功'));
            }
        });
    }

    getPageJSON = (page, readonly) => {
        this.oldPage = page;
        const { json } = page;
        const { sheets } = json;
        each(sheets, (sheet, name) => {
            const { data } = sheet;
            const { dataTable } = data;
            each(dataTable, (rowData, row) => {
                each(rowData, (cellData, col) => {
                    const { style = {} } = cellData;
                    const { cellType } = style;
                    if (cellType) {
                        delete style.backgroundImage;
                        delete style.backgroundImageLayout;
                        delete style.textIndent;
                        const { fieldType } = cellType;
                        if (fieldType) {
                            const [htmltype, type] = fieldType;
                            style.locked = this.readonly;
                            if (!cellType.viewAttr) {
                                cellType.viewAttr = 2;
                            }
                            if (this.readonly) {
                                cellType.viewAttr = 1;
                            }
                            if (htmltype === 'select') {
                                if (cellType.viewAttr == 1) {
                                    cellType.typeName = 'WeaSelectReadonlyCellType';
                                } else {
                                    cellType.typeName = 'WeaSelectCellType';
                                }
                            } else if (htmltype === 'check') {
                                cellType.typeName = 'WeaCheckboxCellType';
                            } else if (htmltype === 'browser') {
                                const { value = '' } = type || {};
                                if (value === '2' || value === '290') {
                                    cellType.typeName = 'WeaDatePickerCellType';
                                } else if (value === '258' || value === '2222' || value === '58' || value === '263') {
                                    cellType.typeName = 'WeaCityPickerCellType';
                                } else if (value === '19') {
                                    cellType.typeName = 'WeaTimePickerCellType';
                                } else {
                                    cellType.typeName = 'WeaBrowserCellType';
                                }
                            } else if (htmltype === 'upload') {
                                if (type === 'image') {
                                    cellType.typeName = 'WeaPicCellType';
                                }
                            } else {
                                cellType.typeName = 'WeaInputCellType';
                                style.formatter = "@";
                            }
                        } else if (cellType.typeName === 'NoFieldCellType') {
                            cellType.display = true;
                        }
                    }
                });
            });

        });
        return json;
    }

    showPage = (page) => {
        if (!this.workbook) {
            setTimeout(() => {
                this.showPage(page);
            }, 50);
            return;
        }
        window.excel = new Excel(this);
        const json = this.getPageJSON(page);
        let tmpDataSource = page.dataSource;
        // if(this.bindingVersionData) {
        //     tmpDataSource = this.versionDatasource;
        //     this.bindingVersionData = false;
        // }
        
        const dataSource = window.dataSourceInstance = this.dataSourceInstance = new window.GC.Spread.Sheets.Bindings.CellBindingSource(tmpDataSource);
        const WeaSelectReadonlyCellType = window.WeaSelectReadonlyCellType = CellType('WeaSelectReadonlyCellType');
        const WeaInputCellType = window.WeaInputCellType = CellType('WeaInputCellType');
        const WeaCheckboxCellType = window.WeaCheckboxCellType = CellType('WeaCheckboxCellType');
        const WeaBrowserCellType = window.WeaBrowserCellType = CellType('WeaBrowserCellType');
        const WeaSelectCellType = window.WeaSelectCellType = CellType('WeaSelectCellType');
        const NoFieldCellType = window.NoFieldCellType = CellType('NoFieldCellType');
        const WeaCityPickerCellType = window.WeaCityPickerCellType = CellType('WeaCityPickerCellType');
        const WeaPicCellType = window.WeaPicCellType = CellType('WeaPicCellType');
        
        window.WeaDatePickerCellType = CellType('WeaDatePickerCellType');
        window.WeaTimePickerCellType = CellType('WeaTimePickerCellType');
        window.DetailIndexType = CellType('DetailIndexType');
        const FieldCellType = CellType('FieldCellType');
        window.FieldCellType = FieldCellType;
        
        const afters = this.loadFormula();
        const cuscode = page.cuscode ? Base64.decode(page.cuscode) : "";
        this.workbook.suspendPaint();
        this.workbook.fromJSON(json, false);
        this.orgJson = json;

        this.func = [];
        this.clipboardRanges = [];
        this.workbook.options.showDragFillTip = false;
        const spreadJs = window.GC.Spread.Sheets;
        this.workbook.bind(spreadJs.Events.DragFillBlock, this.dragFillBlock);
        this.workbook.bind(spreadJs.Events.CellClick, this.cellClick);
        this.workbook.bind(spreadJs.Events.EnterCell, this.enterCell);
        this.workbook.bind(spreadJs.Events.EditStarting, this.editStarting);
        this.workbook.bind(spreadJs.Events.ActiveSheetChanged, this.activeSheetChange);
        this.workbook.bind(spreadJs.Events.EditEnded, this.editEnded);
        this.workbook.bind(spreadJs.Events.ClipboardChanged, this.ClipboardChanged);
        this.workbook.bind(spreadJs.Events.CellChanged, this.cellChanged);
        this.workbook.bind(spreadJs.Events.RangeChanged, this.rangeChanged);

        // 移动端隐藏横向滚动条
        if(isMobile()) {
            this.workbook.options.showHorizontalScrollbar = false;
           }
        const { sheets = {} } = json;
        this.workbook.sheets.forEach(sheet => {
            const sheetName = sheet.name();
            const sheetObj = sheets[sheetName] || {};
            const { tables = [], data: { dataTable = {} } = {} } = sheetObj;
            const customTables = [];
            sheet.tables.all().forEach((table, tableIndex) => {
                table.filterButtonVisible(false);
                table.autoGenerateColumns(false);
                if (table.bindingPath() && tables.length > tableIndex) {
                    const tableObj = tables[tableIndex] || {};
                    const { columns = [] } = tableObj;
                    
                    const tableColumns = [];
                    const { row: dataRow, col: dataCol } = table.dataRange();
                    const spanKeys = [];
                    this.tableFirstRowHeight[sheetName + '@' +  table.name()] = sheet.getRowHeight(dataRow);
                    columns.forEach((column, columnIndex) => {
                        const { style = {}, formula } = (dataTable[dataRow] || {})[dataCol + columnIndex] || {};
                        const { cellType = {} } = style;

                        if (cellType.combineSameCell) {
                            spanKeys.push({
                                name: cellType.fieldName,
                                index: columnIndex
                            });
                        }
                        if (cellType.typeName) {
                            const CellTypeClass = window[cellType.typeName];
                            if (CellTypeClass) {
                                let cellTypeInstance = new CellTypeClass();
                                cellTypeInstance.fromJSON(cellType);
                                this.func.push({
                                    key: sheetName,
                                    action: () => {
                                        const { rowCount: oldRowCount = 0, row: oldRow = 0 } = table.oldDataRange || {};
                                        let startRow = oldRow + oldRowCount;
                                        const { row, col, rowCount } = table.dataRange();
                                        if (rowCount > oldRowCount) {
                                            // if (cellType.typeName == 'WeaSelectCellType') {
                                            startRow = (startRow === 0 ? row : startRow);
                                            for (let i = 0; i < rowCount; i++) {

                                                cellTypeInstance = new CellTypeClass();
                                                cellTypeInstance.fromJSON(cellType);
                                                if (!sheet.getCell(row + i, col + columnIndex).cellType()) {

                                                    sheet.getCell(row + i, col + columnIndex).cellType(cellTypeInstance);
                                                }
                                            }
                                            //    } 
                                            //     else {
                                            //         sheet.getRange(startRow === 0 ? row : startRow, col + columnIndex, rowCount - oldRowCount, 1).cellType(cellTypeInstance);
                                            //     }

                                        }
                                    }
                                });
                            }
                        }
                        const span = sheet.getSpan(dataRow, dataCol + columnIndex);
                        if (span && span.row === dataRow && span.col === dataCol + columnIndex) {
                            this.func.push({
                                key: sheetName,
                                action: () => {
                                    const { rowCount: oldRowCount = 0 } = table.oldDataRange || {};
                                    const { row, rowCount } = table.dataRange();
                                    if (rowCount > oldRowCount) {
                                        for (let spanIndex = 0; spanIndex < rowCount; spanIndex++) {
                                            sheet.addSpan(row + spanIndex, dataCol + columnIndex, span.rowCount, span.colCount);
                                        }
                                    }
                                }
                            });
                        }
                        styleNames.forEach(styleName => {
                            if (style[styleName] !== void 0) {
                                this.func.push({
                                    key: sheetName,
                                    action: () => {
                                        const { rowCount: oldRowCount = 0, row: oldRow = 0 } = table.oldDataRange || {};
                                        const startRow = oldRow + oldRowCount;
                                        const { row, col, rowCount } = table.dataRange();
                                        if (rowCount > oldRowCount) {
                                            sheet.getRange(startRow === 0 ? row : startRow, col + columnIndex, rowCount - oldRowCount, 1)
                                                ._w(styleName, this.getStyleValue(style, styleName));
                                        }
                                    }
                                });
                            }
                        });
                        this.func.push({
                            key: sheetName,
                            action: () => {
                                const { rowCount: oldRowCount = 0, row: oldRow = 0 } = table.oldDataRange || {};
                                const startRow = oldRow + oldRowCount;
                                const { row, col, rowCount } = table.dataRange();
                                if (formula) {
                                    table.setColumnDataFormula(columnIndex, `=${formula}`)
                                }
                                /* if (rowCount > oldRowCount && formula) {
                                    table.setColumnDataFormula(columnIndex, `=${formula}`)
                                }*/
                                /* if (rowCount > oldRowCount && formula) {
                                    // console.log(formula)
                                    sheet.getRange(startRow === 0 ? row : startRow, col + columnIndex, rowCount - oldRowCount, 1).formula(`=${formula}`);
                                } */
                            }
                        });
                        const tableCol = new window.GC.Spread.Sheets.Tables.TableColumn('' + columnIndex);
                        tableCol.name(column.name);
                        tableCol.dataField(column.dataField);
                        tableColumns.push(tableCol);
                    });

                    const bindpath = table.bindingPath();
                    const records = dataSource.getValue(bindpath) || [];
                    dataSource.setValue(bindpath, sortRecords(records, spanKeys))
                    if (spanKeys.length > 0) {
                        this.func.push({
                            key: sheetName,
                            action: () => {
                                removeAllSpan(sheet, table);
                                this.combineSameCell(sheet, table, spanKeys);
                            }
                        });
                    }
                
                    table.spanKeys = spanKeys;
                    table.bindColumns(tableColumns);
                    table.bindingPath(table.bindingPath());
                } else if(table.name().startsWith("custom") & tables.length > tableIndex) {
                    customTables.push({table,tableIndex});
                    
                    //console.log("此处为自定义明细表",row, rowCount, col, colCount);
                }
            });

            if(customTables.length > 0) {
                customTables.forEach(custable => {
                    const table = custable.table;
                    const tableIndex = custable.tableIndex;
                    this.hasCustomTable = true;
                    const tableObj = tables[tableIndex] || {};
                    const { name } = tableObj;
                    const tableColumns = [];
                    const { row, rowCount, col, colCount } = table.dataRange();
                    let startRow = row;
                    const startCol = col;
                    const spanKeys = [];

                    let currentRow;
                    let currentCol;
                    let firstFieldCellMap = {};
                    let customBindingPath = sheet.name() + ".custom" + name.substring(6);
                    const preBindPath = sheet.name() + ".custom_" + name.substring(6);
                    const cusdatas = dataSource.getValue(customBindingPath);
                    const expandCol = [];
                    const expandRow = [];
                    // 后面需要考虑多扩展字段的情况
                    const downExpandValue = [];
                    let currentT = 0;
                    this.customBindingCurrentT[preBindPath] = currentT;
                    this.customExpandFieldname[preBindPath] = [];
                    this.customExpandCurrent[preBindPath] = 0;
                    // 获取当前的“焦点”
                    let curRow;
                    let curCol;
                    let expandRowCount;
                    // 横向其他字段 // 除第一行外，其他行需要校验其他的横向拓展字段是否相同，不同需要从中间插入(fieldname, row)
                    const otherrightExpand = [];
                    // 所有的纵向扩展的字段（fieldname, col）
                    const downExpand = [];
                    const isFirstCicle = true;

                    // 向下扩展合并单元格的行列数
                    let downExpandspanRowCount = 1;
                    let downExpandspanColCount = 1;
                    let hasDownexp = false;
                    let firstExpandCol;
                    let firstExpandRow;
                    let isFirst = true;
                    let downExpandFirstRow = 0;

                    // 只保留当前向下扩展的末尾值map（后台返回值已经排序了，跟当前值不相同则表明需要换行了）
                    let currentDownExpandValue = {};
                    let expandT = 0;
                    // 绑定第一个区域
                    this.hasdata0 = false;
                    for(let r = 0 ; r < rowCount ; r++) {
                        currentRow = row + r;
                        // 是否存在纵向扩展（存在了的才为一一对应关系）
                        let downExp = false;

                        const data0 = cusdatas && cusdatas.length > 0 ? cusdatas[0] : undefined;
                        
                        for(let c = 0 ; c < colCount ; c++) {

                            currentCol = col +c;
                            const cell = sheet.getCell(Number(currentRow), Number(currentCol));
                            const cellType = cell.cellType();
                            if(cellType) {
                                const bindingPath = cell.bindingPath();

                                const fieldName = this.getFieldName(bindingPath);
                                // 如果是扩展字段。。
                                const expandType = cellType.expandType;

                                let expandstr = "";
                                if((expandType == "2")) {
                                    const span = sheet.getSpan(Number(currentRow), Number(currentCol));
                                    hasDownexp = true;
                                    if(span) {
                                        const {colCount, rowCount, row} = span;
                                        downExpandFirstRow = row;
                                        if(colCount > downExpandspanColCount) {
                                            downExpandspanColCount = colCount;
                                        }
                                        if(rowCount >downExpandspanRowCount) {
                                            downExpandspanRowCount = rowCount;
                                        }
                                    }
                                    if(data0) {
                                        expandCol.push(fieldName +"@"+ currentRow+","+currentCol + "@" + data0[fieldName] + "@first");
                                    } else {
                                        expandCol.push(fieldName +"@"+ currentRow+","+currentCol)
                                    }
                                    expandstr = "@" + expandType;
                                    if(!firstExpandRow) {
                                        firstExpandRow = currentRow;
                                    }
                                    downExpand.push({fieldname:fieldName,col:currentCol});
                                    currentDownExpandValue[fieldName] = data0 ? data0[fieldName] : undefined;
                                    this.customExpandFieldname[preBindPath].push(fieldName);
                                } else if (expandType == "1") {
                                    if(data0) {
                                        expandRow.push(fieldName +"@"+ currentRow+","+currentCol + "@" + data0[fieldName] + "@first");
                                    } else {
                                        expandRow.push(fieldName +"@"+ currentRow+","+currentCol);
                                    }
                                    expandstr = "@" + expandType;
                                    // 还没有向下扩展时，则该字段定为横向扩展的
                                    if(!hasDownexp) {
                                        otherrightExpand.push({fieldname:fieldName,row:currentRow});
                                        this.customExpandFieldname[preBindPath].push(fieldName);
                                        
                                    }
                                    if(!firstExpandCol && !this.specials) {

                                        firstExpandCol = currentCol;
                                        this.specials = false;
                                    }
                                    
                                    curCol = currentCol;
                                    
                                } else {
                                    // if(!curCol) {
                                    //     curCol = currentCol;
                                    //     if(!firstExpandCol) {

                                    //         firstExpandCol = currentCol;
                                    //         this.specials = true;
                                    //         if(!hasDownexp) {
                                    //             this.customExpandFieldname[preBindPath].push(fieldName);
                                    //         }
                                    //     }
                                    // }
                                }
                                // 第一次出现的字段赋值
                                if(!firstFieldCellMap[fieldName]) {
                                    firstFieldCellMap[fieldName] = currentRow + "@" + currentCol + expandstr;
                                    // 单独绑定
                                    if(this.customExpandFieldname[preBindPath].indexOf(fieldName) > -1) {
                                        this.customExpandCurrent[preBindPath] = this.customExpandCurrent[preBindPath] + 1;
                                        const bpath = preBindPath +'h'+ ".t"+this.customExpandCurrent[preBindPath]+"."+ fieldName;
                                        cell.bindingPath(bpath);
                                        if(data0){

                                            dataSource.setValue(bpath, data0[fieldName]);
                                        }
                                    } else {
                                        cell.bindingPath(preBindPath + ".t"+currentT+"."+ fieldName);
                                        //this.setCellType(sheet.name(),cell);
                                        if(data0 && !this.hasdata0) {
                                            const p = preBindPath + ".t0";
                                            dataSource.setValue(p, data0);
                                            this.hasdata0 = true;
                                            sheet.getCell(Number(currentRow), Number(currentCol)).value(data0[fieldName]);
                                            
                                            downExpandValue.push(data0[fieldName]);
                                        }
                                    }
                                    
                                }
                                
                                
                            }

                        }
                        
                    }
                    this.otherrightExpandMap[customBindingPath] = otherrightExpand;
                    if(cusdatas && cusdatas.length > 0 && expandCol.length > 0) {
                        // 获取当前的“焦点”
                        curRow = Number(expandCol[expandCol.length-1].split("@")[1].split(",")[0]);
                        //curCol = Number(expandRow[expandRow.length-1].split("@")[1].split(",")[1]);
                        for(let i = 1 ; i < cusdatas.length; i++) {
                            
                            currentT = this.customBindingCurrentT[preBindPath] + 1;
                            this.customBindingCurrentT[preBindPath] = currentT;
                            const data = cusdatas[i];
                            // 横向看向下扩展的值有没有存在，不存在需要向下扩展
                            let hasvalue = true;
                            // //let isFirst = false;
                            // let rowcol;
                            // for(let ec = 0 ; ec < expandCol.length ; ec++) {

                            //     const colstrs = expandCol[ec].split("@");
                            //     if(data[colstrs[0]] == colstrs[2]) {
                            //         hasvalue = true;
                            //         // if(colstrs.length == 4) {
                            //         //     isFirst = true;
                            //         // }
                            //         rowcol = colstrs[1].split(",");
                            //         break;
                            //     }
                                
                            // }
                            // 判断纵向扩展值是否都相等
                            for(let key in currentDownExpandValue) {

                                if(!this.isObjectValueEqual(data[key], currentDownExpandValue[key], true) ) {
                                    hasvalue = false;
                                }

                            }


                            // let span;
                            // if(!expandRowCount) {

                            //     span = sheet.getSpan(Number(rowcol[0]),Number(rowcol[1]));
                            // }
                            // jia
                            let maxrow = curRow + downExpandspanRowCount;
                            // if(span) {
                            //     const {row, rowCount} = span;
                            //     expandRowCount = rowCount;
                            //     maxrow = row + rowCount - 1;
                            // }

                            // 先算第一行的，其他行的在考虑。。。
                            let rcount = maxrow - startRow;

                            if(!hasvalue) {
                                isFirst = false;
                                // *****此处逻辑不对：复制完以后不一定就是第一列能匹配上，有待商榷，而且所有格子都需要重新绑定,处理与纵向类似
                                const {rowCount, colCount, row, col} = table.dataRange();
                                // 先resize再赋值
                                sheet.addRows(curRow + downExpandspanRowCount,downExpandspanRowCount );
                                sheet.tables.resize(table,rowCount + downExpandspanRowCount, colCount);
                                sheet.copyTo(Number(curRow), col, Number(curRow) + downExpandspanRowCount, col, downExpandspanRowCount, colCount, window.GC.Spread.Sheets.CopyToOptions.all);

                                // 配置相同的行高
                                this.setSameHeight(sheet, curRow, downExpandspanRowCount);
                                // 当前起始row，col游标变化
                                startRow = curRow = Number(curRow) + downExpandspanRowCount;
                                curCol = col;
                                currentRow = curRow;
                                // 处理该段区域首个值
                                
                                let complete = false;
                                // 第一列值完成后，跳出（用处不大）
                                for(let c = 0 ; c < colCount ; c++) {

                                    currentCol = col +c;
                                    const cell = sheet.getCell(Number(currentRow), Number(currentCol));
                                    const cellType = cell.cellType();
                                    if(cellType) {
                                        const bindingPath = cell.bindingPath();
    
                                        const fieldName = this.getFieldName(bindingPath);
                                        // 如果是扩展字段。。
                                        const expandType = cellType.expandType;
    
                                        let expandstr = "";
                                        if((expandType == "2")) {
                                            expandCol.push(fieldName +"@"+ currentRow+","+currentCol + "@" + data[fieldName])
                                            expandstr = "@" + expandType;

                                            this.setCellType(sheet.name(),sheet.getCell(Number(currentRow)-downExpandspanRowCount, Number(currentCol)),cell);
                                            this.customExpandCurrent[preBindPath] = this.customExpandCurrent[preBindPath] +1;
                                            const path = preBindPath +'h' +".t"+this.customExpandCurrent[preBindPath]+"."+ this.getFieldName(cell.bindingPath());
                                            dataSource.setValue(path, data[fieldName])
                                            cell.bindingPath(path);

                                        } else if (expandType == "1") {
                                            expandRow.push(fieldName +"@"+ currentRow+","+currentCol + "@" + data[fieldName]);
                                            
                                            expandstr = "@" + expandType;
                                            //curCol = currentCol;
                                            // 找到第一个有效列则推出
                                            complete = true;
                                        }
                                        
                                        // 此处应该走不到，到时候去掉
                                        if(!firstFieldCellMap[fieldName]) {
                                            firstFieldCellMap[fieldName] = currentRow + "@" + currentCol + expandstr;
                                            if(this.customExpandFieldname[preBindPath].indexOf(fieldName) > -1) {
                                                this.customExpandCurrent[preBindPath] = this.customExpandCurrent[preBindPath] + 1
                                                cell.bindingPath(preBindPath + 'h'+".t"+this.customExpandCurrent[preBindPath]+"."+ fieldName);
                                            } else {
                                                cell.bindingPath(preBindPath +".t"+currentT+"."+ fieldName);
                                            }
                                            //this.setCellType(sheet.name(),cell);
                                            if(data) {
                                                sheet.getCell(Number(currentRow), Number(currentCol)).value(data[fieldName]);
                                                
                                                downExpandValue.push(data[fieldName]);
                                            }
                                        }
                                        
                                        
                                    }

                                    if(complete)
                                    break;
    
                                }
                                curCol = firstExpandCol;
                                for(let c = firstExpandCol ; c < col + colCount ; c++) {
                                    
                                    if(sheet.getCell(Number(startRow)-downExpandspanRowCount, Number(c)).cellType()) {
                                        const p = preBindPath + ".t"+(currentT++);
                                        //纵向的应该与该行的值相等
                                        for(let j = 0 ; j < downExpand.length; j++) {
                                            const {fieldname,col} = downExpand[j];
                                            // ****此处取的每个循环的第一层，还是要注意，纵向扩展数据不一定都在这一行
                                            dataSource.setValue(p+"."+fieldname,data[fieldname])
                                        }
                                        // 横向与该列的值相等
                                        for(let j = 0 ; j < otherrightExpand.length; j++) {
                                            const {fieldname,row} = otherrightExpand[j];
                                            let expandCell = sheet.getCell(row, c);
                                            const span = sheet.getSpan(row, c);
                                            if(span) {
                                                expandCell = sheet.getCell(span.row, span.col);
                                            }
                                            const bindingPath = expandCell.bindingPath();
                                            // ****此处取的每个循环的第一层，还是要注意，纵向扩展数据不一定都在这一行
                                            dataSource.setValue(p+"."+fieldname,dataSource.getValue(bindingPath));
                                        }
                                        for(let r = 0 ; r < downExpandspanRowCount ; r ++) {
                                            let cr = startRow + r;
                                            const cell = sheet.getCell(cr,Number(c));
                                            if(c == firstExpandCol) {
                                                this.setCellType(sheet.name(),sheet.getCell(Number(cr)-downExpandspanRowCount, Number(c)),cell);

                                            }else {
                                                this.setCellType(sheet.name(),sheet.getCell(Number(cr),Number(c)-1),cell);
                                            }
                                            
                                            if(cell.bindingPath()) {

                                                cell.bindingPath(p+"."+ this.getFieldName(cell.bindingPath()));
                                            }
                                        }
                                    }
                                    

                                }

                                for(let key in currentDownExpandValue) {
                                    // 塞最新的值
                                    currentDownExpandValue[key] = data[key]

                                }
                                this.customBindingCurrentT[preBindPath] = currentT;
                            }

                            if(isFirst) {
                                
                                // 先resize再赋值
                                curCol = curCol + 1;
                                const {colCount} = table.dataRange();
                                sheet.addColumns(curCol, 1);
                                sheet.tables.resize(table,rowCount, colCount + 1);
                                sheet.copyTo(Number(startRow), Number(curCol-1), Number(startRow), Number(curCol), rcount, 1, window.GC.Spread.Sheets.CopyToOptions.all);
                                sheet.setColumnWidth(Number(curCol), sheet.getColumnWidth(Number(curCol)-1));
                                const p = preBindPath + ".t"+currentT;
                                dataSource.setValue(p, data);
                                //dataSource.setValue(ph, data);
                                // celltype保持一致
                                for(let r = 0 ; r < rcount ; r ++) {
                                    let cr = startRow + r;
                                    this.setCellType(sheet.name(),sheet.getCell(cr,Number(curCol)-1),sheet.getCell(cr,Number(curCol)));
                                    
                                    const bpath = sheet.getCell(cr,Number(curCol)-1).bindingPath();
                                    if(bpath) {
                                        
                                        const cell = sheet.getCell(cr,Number(curCol));
                                        const fieldname = this.getFieldName(bpath);
                                        if(!fieldname) {
                                            continue;
                                        }
                                        let bdPath = '';
                                        if(this.customExpandFieldname[preBindPath].indexOf(fieldname) > -1) {
                                            this.customExpandCurrent[preBindPath] = this.customExpandCurrent[preBindPath] + 1;
                                             bdPath = preBindPath + "h" + ".t"+this.customExpandCurrent[preBindPath]+'.'+fieldname ;
                                             dataSource.setValue(bdPath,data[fieldname]);
                                        } else {

                                             bdPath = p+"."+ fieldname;                                  
                                        }
                                        sheet.getCell(cr,Number(curCol)).bindingPath(bdPath);
                                    }
                                    
                                }
                                // 获取当前的“焦点”
                                //curRow = expandCol[expandCol.length-1].split("@")[1].split(",")[0];
                                //curCol = curCol +1;
                            } else if(!isFirst) {
                                // 先resize再赋值
                                // sheet.addColumns(curCol - startCol+2, 1);
                                // sheet.tables.resize(table,rowCount, curCol - startCol+2);
                                // sheet.copyTo(Number(startRow), Number(curCol), Number(startRow), Number(curCol)+1, rcount, 1, window.GC.Spread.Sheets.CopyToOptions.all);

                                // **** 在此处增加判断抬头是否匹配的场景：不匹配从头开始匹配，匹配不到则在最前面增加一列
                                let matchCol = this.isMatchRight(dataSource,sheet,downExpand,otherrightExpand,startRow, curCol, data,firstExpandRow, firstExpandCol,table,currentT, downExpandspanRowCount, preBindPath);

                                let matchs = (matchCol+'').split("@");
                                let cCurrent;
                                if(matchs.length == 2) {
                                    matchCol = Number(matchs[0]);
                                    cCurrent = matchs[1]
                                }
                                // curretnT变化 说明新增了列，matchCol就是新增出来的列
                                if(currentT != this.customBindingCurrentT[preBindPath] && matchs != 2) {
                                    for(let ct = currentT+1; ct < this.customBindingCurrentT[preBindPath] ;ct++) {
                                        for(let i = 0 ; i < otherrightExpand.length; i++) {
                                            const {fieldname, row:erow} = otherrightExpand[i];
                                            dataSource.setValue((preBindPath + ".t"+ct+"."+fieldname), data[fieldname]);
                                            this.setCellType(sheet.name(),sheet.getCell(Number(erow),Number(matchCol)-1),sheet.getCell(Number(erow),Number(matchCol)));
                                            if(ct ==currentT+1) {

                                                this.customExpandCurrent[preBindPath] = this.customExpandCurrent[preBindPath] + 1;
                                                dataSource.setValue((preBindPath + 'h'+".t"+ this.customExpandCurrent[preBindPath] +"."+fieldname), data[fieldname]);
                                                sheet.getCell(Number(erow), Number(matchCol)).bindingPath(preBindPath + 'h'+".t"+ this.customExpandCurrent[preBindPath] +"."+fieldname);
                                                //sheet.getCell(Number(erow), Number(matchCol)).bindingPath(preBindPath + ".t"+ct+"."+fieldname);
                                            }
                                            
                                        }

                                        // //纵向的应该与该行的值相等
                                        // for(let j = 0 ; j < downExpand.length; j++) {
                                        //     const {fieldname,col} = downExpand[j];
                                        //     // ****此处取的每个循环的第一层，还是要注意，纵向扩展数据不一定都在这一行
                                        //     dataSource.setValue(preBindPath + ".t"+ct+"."+fieldname,data[fieldname])
                                        // }
                                    }
                                    
                                } else {

                                }

                                currentT = this.customBindingCurrentT[preBindPath];
                                //const matchCol = curCol;
                                // celltype保持一致
                                const p = preBindPath +(cCurrent ? "." + cCurrent : ".t" +currentT);
                                dataSource.setValue(p, data);
                                for(let r = 0 ; r < downExpandspanRowCount ; r ++) {
                                    let cr = startRow + r;
                                    const cell = sheet.getCell(cr,Number(matchCol));
                                    //this.setCellType(sheet.name(),sheet.getCell(cr,Number(matchCol)-1),cell);
                                 if(cell.bindingPath()) {

                                    cell.bindingPath(p+"."+ this.getFieldName(cell.bindingPath()));
                                 }
                                }
                                // 获取当前的“焦点”
                                //curRow = expandCol[expandCol.length-1].split("@")[1].split(",")[0];
                                if(matchCol <=curCol) {

                                    curCol = curCol +1;
                                }
                            }else{
                                // // *****此处逻辑不对：复制完以后不一定就是第一列能匹配上，有待商榷，而且所有格子都需要重新绑定,处理与纵向类似
                                // const {rowCount, colCount, row, col} = table.dataRange();
                                // // 先resize再赋值
                                // sheet.addRows(rowCount,downExpandspanRowCount );
                                // sheet.tables.resize(table,row + rowCount + downExpandspanRowCount, colCount);
                                // sheet.copyTo(Number(curRow), col, Number(curRow) + downExpandspanRowCount, col, downExpandspanRowCount, colCount, window.GC.Spread.Sheets.CopyToOptions.all);

                                // // 当前起始row，col游标变化
                                // startRow = curRow = Number(curRow) + downExpandspanRowCount;
                                // curCol = col;
                                // currentRow = curRow;
                                // console.log("当前坐标",curRow, curCol,table.dataRange());
                                // // 处理该段区域首个值
                                
                                // let complete = false;
                                // // 第一列值完成后，跳出（用处不大）
                                // for(let c = 0 ; c < colCount ; c++) {

                                //     currentCol = col +c;
                                //     const cell = sheet.getCell(Number(currentRow), Number(currentCol));
                                //     const cellType = cell.cellType();
                                //     if(cellType) {
                                //         const bindingPath = cell.bindingPath();
    
                                //         const fieldName = this.getFieldName(bindingPath);
                                //         // 如果是扩展字段。。
                                //         const expandType = cellType.expandType;
    
                                //         let expandstr = "";
                                //         if((expandType == "2")) {
                                //             expandCol.push(fieldName +"@"+ currentRow+","+currentCol + "@" + data[fieldName])
                                //             expandstr = "@" + expandType;

                                //             this.setCellType(sheet.name(),sheet.getCell(Number(currentRow)-downExpandspanRowCount, Number(currentCol)),cell);
                                //             const path = preBindPath + ".t"+currentT+"."+ this.getFieldName(cell.bindingPath());
                                //             dataSource.setValue(path, data[fieldName])
                                //             cell.bindingPath(path);

                                //         } else if (expandType == "1") {
                                //             expandRow.push(fieldName +"@"+ currentRow+","+currentCol + "@" + data[fieldName]);
                                            
                                //             expandstr = "@" + expandType;
                                //             curCol = currentCol;
                                //             // 找到第一个有效列则推出
                                //             complete = true;
                                //         }
                                        
                                        
                                //         if(!firstFieldCellMap[fieldName]) {
                                //             firstFieldCellMap[fieldName] = currentRow + "@" + currentCol + expandstr;
                                //             cell.bindingPath(preBindPath + ".t"+currentT+"."+ fieldName);
                                //             //this.setCellType(sheet.name(),cell);
                                //             if(data) {
                                //                 sheet.getCell(Number(currentRow), Number(currentCol)).value(data[fieldName]);
                                                
                                //                 downExpandValue.push(data[fieldName]);
                                //             }
                                //         }
                                        
                                        
                                //     }

                                //     if(complete)
                                //     break;
    
                                // }


                                // for(let c = curCol ; c < colCount ; c++) {
                                    
                                //     const p = preBindPath + ".t"+(currentT++);
                                //     for(let r = 0 ; r < downExpandspanRowCount ; r ++) {
                                //         let cr = startRow + r;
                                //         const cell = sheet.getCell(cr,Number(c));
                                        
                                //         if(c == curCol) {
                                //             this.setCellType(sheet.name(),sheet.getCell(Number(cr)-downExpandspanRowCount, Number(c)),cell);

                                //         }else {
                                //             this.setCellType(sheet.name(),sheet.getCell(Number(cr),Number(c)-1),cell);
                                //         }
                                        
                                        
                                        
                                //         cell.bindingPath(p+"."+ this.getFieldName(cell.bindingPath()));
                                //     }

                                // }

                                // this.customBindingCurrentT[preBindPath] = currentT;
                                
                            }

                        }

                    }

                    
                    const { row:tableRow, rowCount:tableRowCount, col:tableCol, colCount:tableColCount } = table.dataRange();
                    otherrightExpand.forEach(expand => {
                        const {fieldname, row} = expand;
                        let lastValue;
                        for(let c = tableCol; c < tableColCount + tableCol; c++) {
                            const cell = sheet.getCell(row, c);
                            const bpath = cell.bindingPath();
                            const cellType = cell.cellType();
                            const combineSameCell = cellType ? cellType.combineSameCell : false;
                            const value = bpath ? dataSource.getValue(bpath) : undefined;
                            if(combineSameCell && lastValue && this.isObjectValueEqual(lastValue ,value,true)) {
                                const span = sheet.getSpan(row, c-1);
                                if(span) {
                                    //const {row:spanRow,col:,rowCount,colCount} = span;
                                    sheet.addSpan(span.row,span.col,span.rowCount,span.colCount+1);
                                    //sheet.removeSpan(row, col-1);
                                } else {
                                    sheet.addSpan(row,c-1,1,2);
                                }

                            } 
                                lastValue = value;
                            

                        } 
                    })

                    downExpand.forEach(expand => {
                        const {fieldname, col} = expand;
                        let lastValue;
                        for(let r = tableRow; r < tableRowCount + tableRow; r++) {
                            const span = sheet.getSpan(r, col);
                            let count = 1;
                            let cell;
                            if(span) {
                                if(r == span.row) {
                                    cell = sheet.getCell(span.row, span.col);
                                    count = span.rowCount;
                                } else {
                                    continue;
                                }
                            } else {
                                cell = sheet.getCell(r, col);
                            }
                            

                            const bpath = cell.bindingPath();
                            const cellType = cell.cellType();
                            const combineSameCell = cellType ? cellType.combineSameCell : false;
                            const value = bpath ? dataSource.getValue(bpath) : undefined;
                            if(combineSameCell && lastValue && this.isObjectValueEqual(lastValue,value,true)) {
                                const span = sheet.getSpan(r-1, col);
                                if(span) {
                                    //const {row:spanRow,col:,rowCount,colCount} = span;
                                    sheet.addSpan(span.row,span.col,span.rowCount + count,span.colCount);
                                    //sheet.removeSpan(row, col-1);
                                } else {
                                    sheet.addSpan(r-1,col,2,1);
                                }

                            }
                                lastValue = value;
                            

                        } 
                    })

                })
            }

            if (sheet.getColumnCount() < 50) {
                sheet.setColumnCount(50);
            }
            if (sheet.getRowCount() < 200) {
                sheet.setRowCount(200);
            }
            sheet.setDataSource(dataSource);

        });
        // 预先遍历下
        const activeIndex = this.workbook.getActiveSheetIndex();
        this.workbook.sheets.forEach((sheet, index) => {
            if(this.workbook.getSheet(index).visible()){
                this.workbook.getTab().KD(index);
            }
        })
        this.workbook.setActiveSheetIndex(activeIndex);
        this.calcAll(true, this.workbook.getActiveSheet().name());
        register(this.workbook.commandManager(), this);
        this.reEnterCell();
        const sheet = this.workbook.getActiveSheet();
        if(this.autoFitSheetMap && this.autoFitSheetMap[sheet.name()]) {
            this.workbook.commandManager().autoFitRow.j4.canUndo = false;
            this.setAutoFitRow(sheet)
            this.workbook.commandManager().autoFitRow.j4.canUndo = true;
        }
        
        this.workbook.resumePaint();
        afters.forEach(after => after());
        // 只读情况下不走该方法
        if (!this.readonly) {
            this.initstatus = true;
            this.changeSelectTypeValue();
            this.initstatus = false;
        }
        API.getExcelPageCustomCode(this.params).then((cuscode) => {
            this.initCusCode(cuscode);
        });
        if (this.showDefault && !this.hasData) {
            API.getExcelPageFieldAssignDatas(this.params).then(result => {
                this.triggerFieldAssign(true);
                if (result) {
                    this.getFieldInfoMap();
                    this.workbook.suspendPaint();
                    const mainfield = result.mainfield;
                    if (this.mainFieldInfoMap) {
                        each(this.mainFieldInfoMap, (mainMapSheet, sheetname) => {
                            const mainsheet = mainfield[sheetname];
                            if (mainsheet) {
                                each(mainMapSheet, (fieldindex, fieldname) => {
                                    const value = mainsheet[fieldname];
                                    const { row, col } = fieldindex;
                                    const sheet = this.workbook.getSheetFromName(sheetname);
                                    console.log(value, row, col, sheet);
                                    if (typeof value != 'undefined') {
                                        sheet.getCell(Number(row), Number(col)).value(value);
                                    }
                                });
                            }
                        });
                    }

                    const detailfield = result.detailfield;
                    if (this.detailFieldInfoMap) {
                        each(this.detailFieldInfoMap, (detailMapSheet, sheetname) => {
                            const detailsheet = detailfield[sheetname];
                            const sheet = this.workbook.getSheetFromName(sheetname);
                            if (detailsheet) {
                                //有序遍历明细表，从下到上
                                for (let i = 0, len = detailMapSheet.length; i < len; i++) {
                                    const { tablename, detailname, dataCount, fieldindex, row } = detailMapSheet[i];
                                    const detail = detailsheet[detailname];
                                    if (detail && fieldindex) {
                                        //初始化明细表行
                                        let lengthArr = [0];
                                        for (let key in detail) {
                                            lengthArr.push(detail[key].length);
                                        }
                                        const valueCount = Math.max(...lengthArr);
                                        const bindingPath = sheetname + '.' + detailname;
                                        let totalCount = valueCount;
                                        const rowCount = this.getRowCount(sheetname, bindingPath);
                                        let newValue = [];
                                        let defaultCount = 0;
                                        if (totalCount > rowCount) {
                                            for (let j = 0; j < totalCount; j++) {
                                                newValue.push({ detail_index: j + 1 });
                                            }
                                            defaultCount = totalCount;
                                        } else {
                                            for (let j = 0; j < rowCount; j++) {
                                                newValue.push({ detail_index: j + 1 });
                                            }
                                            defaultCount = rowCount;
                                        }
                                        this.dataSourceInstance.setValue(bindingPath, newValue);
                                        const table = sheet.tables.findByName(tablename);
                                        table.bindingPath(bindingPath);
                                        this.calcAll(true, sheetname);
                                        let startRow = 0;
                                        for (let key in fieldindex) {
                                            const { row } = fieldindex[key];
                                            startRow = row;
                                            this.setUserinfo2newRow(table, startRow, defaultCount);
                                            break;
                                        }

                                        each(fieldindex, (o, fieldname) => {
                                            const value = detail[fieldname];//明细表字段数组
                                            const { row, col } = o;//明细表初始行列
                                            if (typeof value != 'undefined' && value.length > 0) {
                                                for (let i = 0; i < value.length; i++) {
                                                    sheet.getCell(Number(startRow) + i, Number(col)).value(value[i]);
                                                }

                                            }
                                        });
                                        this.setDetailTableRowHeight();
                                    }
                                }
                            }
                        });
                    }
                    this.workbook.resumePaint();
                    // this.getFieldAssignList(changeFieldList);
                }
                // this.triggerFieldAssign(true);
                this.setDetailTableRowHeight();
            })
            //初始化过滤条件赋值中条件有值的记录，主动请求触发联动
            // this.initFieldAssign();
            // this.triggerFieldAssign(true);
        }

        this.setDetailTableRowHeight();
        //任务填报页面初始化加载渲染图片字段
        setTimeout(this.loadPictures,500);

        this.workbook.options.newTabVisible = false;
        this.workbook.options.allowUserDragDrop = false;
        this.loading = false;
    }

    getFieldName = (bindingPath) => {

        if(bindingPath) {
            let strs = bindingPath.split(".");
            return strs[strs.length-1];
        } else {
            return null;
        }

    }

    getCurrentT = (bindingPath) => {

        let strs = bindingPath.split(".");
        return strs[2];

    }

    setCellType = (sheetName, cell, toCell) => {
        const cellType = cell.cellType();
        if (cellType && cellType.typeName) {
            const CellTypeClass = window[cellType.typeName];
            if (CellTypeClass) {
                let cellTypeInstance = new CellTypeClass();
                cellTypeInstance.fromJSON(cellType);
                toCell.cellType(cellTypeInstance);
                  
            }
        }
    }

    //是否横向匹配
    isMatchRight = (dataSource,sheet,downExpand, otherrightExpand,curow, col, data, firstRow, firstCol,table, currentT, downExpandspanRowCount, preBindPath) => {
        // 此处来匹配

        let length = otherrightExpand.length;
        let match = true;
        let hasBinding = false;
        for(let i = 0 ; i <length ; i ++) {
            const {fieldname, row} = otherrightExpand[i];
            const expandCell = sheet.getCell(Number(row), Number(col));
            if(!this.isObjectValueEqual(dataSource.getValue(expandCell.bindingPath()),data[fieldname],true)) {
                console.log(dataSource.getValue(expandCell.bindingPath()),data[fieldname]);
                match = false;
            }
        }
        
        // 如果匹配，判断该列是否已经绑定了存在值
        const bdPath = sheet.getCell(curow, col).bindingPath();
        // 当前的目标t的值
        let ccurrentT;
        if(bdPath) {
            ccurrentT = this.getCurrentT(bdPath);
            if(this.dataSourceInstance.getValue(preBindPath +"."+ ccurrentT + ".detail_index")) {
                hasBinding = true;
            }
        }

        if(match && !hasBinding) {
            return col+"@"+ccurrentT;
        } else {
            // 不匹配的情况下，从初始列开始往后查
            const { row :startRow,rowCount,col: tableCol, colCount } = table.dataRange();

            // 匹配数量
            let matchCount = 0;
            // 当前匹配数量
            let curCount = 0;
            // 最后一个有效列
            let mCol = 0;
            for(let j = Number(firstCol); j < tableCol + colCount ; j++) {
                    let hasExist = true;
                    curCount = 0;
                    for(let k = 0 ; k < length ; k ++) {
                        const {fieldname, row} = otherrightExpand[k];
                        const cCell = sheet.getCell(Number(row),j);
                        if(cCell.cellType()) {
                            mCol = j;
                        } else {
                            break;
                        }
                        if(!this.isObjectValueEqual(dataSource.getValue(cCell.bindingPath()), data[fieldname])) {
                            hasExist = false;
                        } else {
                            // 满足的个数+1
                            curCount= curCount +1;
                            
                        }
                    }
                    if(curCount == length) {
                        // 如果完全匹配
                        const bdPath = sheet.getCell(curow, j).bindingPath();
                        ccurrentT = this.getCurrentT(bdPath);
                        // 如果不存在值，则该列可以用来绑定数据
                        if(this.dataSourceInstance.getValue(preBindPath +"."+ ccurrentT + ".detail_index")) {
                            
                        } else {
                            return j+"@"+ccurrentT;
                        }
                    }
            
                    if(curCount > matchCount) {
                        matchCount = curCount;
                    } else if(curCount < matchCount) {
                        // 说明需要在此行前面插入
                        this.addCustomDtailColumn(dataSource,sheet,downExpand, table, startRow, tableCol, j,rowCount, firstRow, currentT, downExpandspanRowCount, preBindPath,otherrightExpand,data);
                        return j;
                        
                    }
                
            }
            
            // 执行到这边说明没有匹配到，就在此处（最后一列添加）
            this.addCustomDtailColumn(dataSource,sheet,downExpand, table, startRow, tableCol, mCol+1,rowCount, firstRow, currentT, downExpandspanRowCount, preBindPath,otherrightExpand,data);
            return mCol+1;
        }
    }

    addCustomDtailColumn = (dataSource,sheet,downExpand, table, startRow,startCol, curCol, rcount, firstRow, currentT, downExpandspanRowCount, preBindPath,otherrightExpand,data) => {
        // 先resize再赋值
        
        const {rowCount,colCount} = table.dataRange();
        sheet.addColumns(curCol, 1);
        sheet.tables.resize(table,rowCount, colCount + 1);
        // 去除已存在的合并单元格
        this.removeExistSpans(sheet, Number(curCol), Number(startRow), 1, rcount);
        sheet.copyTo(Number(startRow), Number(curCol)-1, Number(startRow), Number(curCol), rcount, 1, window.GC.Spread.Sheets.CopyToOptions.all);
        sheet.setColumnWidth(Number(curCol), sheet.getColumnWidth(Number(curCol)-1));

        // 绑定
        this.bindingPath4Col(dataSource,sheet,downExpand, table, curCol, rcount, firstRow, currentT, downExpandspanRowCount, preBindPath,otherrightExpand,data);
    }

    // 去除已存在的合并单元格
    removeExistSpans = (sheet, col, row, colCount, rowCount) => {
        for(let r = row ; r < row + rowCount; r++) {
            for(let c = col; c <col + colCount; c++) {
                const span = sheet.getSpan(r, c);
                        if(span) {
                            sheet.removeSpan(r, c);
                        }
            }
        }
    }

    bindingPath4Col = (dataSource,sheet,downExpand, table, curCol, rcount, firstRow, currentT, downExpandspanRowCount, preBindPath,otherrightExpand,data) => {
        // 整个列做绑定操作
        const {row, rowCount, col, colCount} = table.dataRange();
        
        // for(let r = row ; r < firstRow ; r ++) {
        //     console.log("????走不走",r ,curCol)
        //     const cell = sheet.getCell(Number(r), Number(curCol));
        //     if(cell.cellType() && cell.bindingPath()) {
        //         const fieldname = this.getFieldName(cell.bindingPath());
        //         if(!fieldname) {
        //             continue;
        //         }
        //         let bdPath;
        //         if(this.customExpandFieldname[preBindPath].indexOf(fieldname) > -1) {
        //             this.customExpandCurrent[preBindPath] = this.customExpandCurrent[preBindPath] + 1;
        //              bdPath = preBindPath + "h" + ".t"+this.customExpandCurrent[preBindPath]+'.'+fieldname ;
        //              sheet.getCell(r,Number(curCol)).bindingPath(bdPath);
        //         }
        //     }
        // }

        for(let r = firstRow; r < row + rowCount; r = r + downExpandspanRowCount) {

            let isFirst = false;
            for(let c = 0 ; c < downExpandspanRowCount ; c++) {
                const cr = Number(r) + c;
                const cell = sheet.getCell(Number(cr), Number(curCol));
                if(c == 0 && cell.cellType()) {
                    currentT = currentT + 1;
                    isFirst = true;
                } else {
                    isFirst = false;
                }
                
                const p = preBindPath + ".t"+currentT;
                this.setCellType(sheet.name(),sheet.getCell(cr,Number(curCol)-1),sheet.getCell(cr,Number(curCol)));
                const fieldname = this.getFieldName(sheet.getCell(cr,Number(curCol)).bindingPath());
                if(!fieldname) {
                    continue;
                }
                let bdPath;
                if(this.customExpandFieldname[preBindPath].indexOf(fieldname) > -1) {
                    this.customExpandCurrent[preBindPath] = this.customExpandCurrent[preBindPath] + 1;
                     bdPath = preBindPath + "h" + ".t"+this.customExpandCurrent[preBindPath]+'.'+fieldname ;
                } else {

                    bdPath = p+"."+ fieldname;
                }

                sheet.getCell(cr,Number(curCol)).bindingPath(bdPath);
                
                if(isFirst) {
                    //纵向的应该与该行的值相等
                    for(let j = 0 ; j < downExpand.length; j++) {
                        const {fieldname,col} = downExpand[j];
                        let expandCell = sheet.getCell(cr, col);
                        const span = sheet.getSpan(cr, col);
                        if(span) {
                            expandCell = sheet.getCell(span.row, span.col);
                        }
                        const bindingPath = expandCell.bindingPath();
                        // ****此处取的每个循环的第一层，还是要注意，纵向扩展数据不一定都在这一行
                        dataSource.setValue(preBindPath + ".t"+currentT+"."+fieldname,dataSource.getValue(bindingPath))
                    }

                }
            }
        }
        
        this.customBindingCurrentT[preBindPath] = currentT;
    }

    setNotFirstCellType = (sheetName, cell) => {
        const cellType = cell.cellType();
        if (cellType.typeName) {
            const CellTypeClass = window[cellType.typeName];
            if (CellTypeClass) {
                let cellTypeInstance = new CellTypeClass();
                cellTypeInstance.fromJSON(cellType);
                cell.cellType(cellTypeInstance);
                  
            }
        }
    }

    setAutoFitRow = (sheet) => {
        for (var i = 0; i < sheet.getRowCount(); i++) {
            const oldHeight = sheet.getRowHeight(i);

            sheet.autoFitRow(i);

            const newHeight = sheet.getRowHeight(i);

            if(oldHeight > newHeight) {
                sheet.setRowHeight(i, oldHeight);
            }
        }
    }

    // 设置明细表行高与首行保持一致
    setDetailTableRowHeight = (startRow,newRowCount) => {
        this.workbook.suspendPaint();
        this.workbook.sheets.forEach(sheet => {
            const sheetName = sheet.name();
            sheet.tables.all().forEach((table, tableIndex) => {
                // 普通明细表
                if (table.bindingPath()) {
                    
                    const tableName = table.name();
                    const firstRowHeight = this.tableFirstRowHeight[sheetName + '@' + tableName];
                    if(firstRowHeight) {
                        const {row, rowCount} = table.dataRange();
                        for(let r = row ; r < row + rowCount ; r++) {
                            if(startRow && newRowCount) {
                                if(r >= startRow && r < startRow + newRowCount) {
                                    const currentHeight = sheet.getRowHeight(r);
                                    if(currentHeight  < firstRowHeight) {
                                        sheet.setRowHeight(r, firstRowHeight);
                                    }
                                }
                            } else {
                                const currentHeight = sheet.getRowHeight(r);
                                if(currentHeight  < firstRowHeight) {
                                    sheet.setRowHeight(r, firstRowHeight);
                                }
                            }
                            
                        }
                    }
                }
            });
        });
        this.workbook.resumePaint();
    }


    @action
    loadFormula = () => {
        if (this.customFuns) {
            return this.customFuns.map(obj => {
                const TempFunction = CustomFunction(obj);
                return () => {
                    const func = new TempFunction(
                        obj.name, 0, 0, { name: obj.name, description: obj.describes }
                    );
                    this.workbook.addCustomFunction(func);
                };
            });
        }
        return [];
    }

    initCusCode = (cuscode) => {
        if (cuscode) {
            try {
                jQuery('<div class="edc-code-eara"/>').appendTo(jQuery(document.body)).html(Base64.decode(cuscode));
            } catch(e){
                message.fail('代码块出错：'+e)
            }
        }
    }

    combineSameCell = (sheet, table, spanKeys) => {
        const range = table.dataRange();
        this.combineRangeSameCell(sheet, range, [...spanKeys])
    }
    combineRangeSameCell = (sheet, range, spanKeys) => {
        const key = spanKeys.shift();
        if (key && range) {
            const { row, col, rowCount, colCount } = range;
            const currentCol = col + key.index;
            const v = sheet.getCell(row, currentCol).value();
            let oldValue = v ? JSON.stringify(v) : v;
            let rowCountToCombine = 1;
            let startRow = row;
            for (let index = 1; index < rowCount; index++) {
                const currentRow = row + index;
                const nv = sheet.getCell(currentRow, currentCol).value();
                const value = nv ? JSON.stringify(nv) : nv;
                if (this.isObjectValueEqual(oldValue,value,true) && value && value != '[]') {
                    rowCountToCombine++;
                } else {
                    if (rowCountToCombine > 1) {
                        sheet.addSpan(startRow, currentCol, rowCountToCombine, 1);
                        this.combineRangeSameCell(sheet, { row: startRow, col, rowCount: rowCountToCombine, colCount }, [...spanKeys]);
                    }
                    startRow = currentRow;
                    rowCountToCombine = 1;
                    oldValue = value;
                }
            }
            if (rowCountToCombine > 1) {
                sheet.addSpan(startRow, currentCol, rowCountToCombine, 1);
                this.combineRangeSameCell(sheet, { row: startRow, col, rowCount: rowCountToCombine, colCount }, [...spanKeys]);
            }
        }
    }
    addDetail = () => {
        if (this.currentTable) {
            const { col, colCount } = this.currentTable.dataRange();
            this['edc.excelView.tableInsertBottomRow'](this.workbook, this.currentRow, col + colCount - 1);
        }
    }
    deleteDetail = () => {
        if (this.currentTable) {
            const { col, colCount } = this.currentTable.dataRange();
            this['edc.excelView.tableDeleteRow'](this.workbook, this.currentRow, col + colCount - 1);
        }
    }

    save = () => {
        this.checkInvalidValue();
        if (!this.doBefore()) {
            return;

        }

        this.loading = true;
        const source = this.dataSourceInstance.getSource();
        ExcelAPI.saveData({
            ...this.params,
            datas: JSON.stringify(source),
            // json: JSON.stringify(this.workbook.toJSON(false)),
            deletedRows: JSON.stringify(this.deletedRows),
        }).then((params) => {
            this.loading = false;
            message.success(getLabel('502231', '保存成功'));
            const urlParams = [];
            each(params, (value, key) => {
                if (typeof value === 'string' || typeof value === 'number') {
                    urlParams.push(`${key}=${value}`);
                }
            });
            if (window.weaHistory) {
                window.weaHistory.push(`${route.excelView}?${urlParams.join('&')}`);
            }

        });
    }


    toEdit = () => {
        const urlParams = [];
            each(this.params, (value, key) => {
                if (typeof value === 'string' || typeof value === 'number') {
                    if(key === 'type') {
                        urlParams.push(`${key}=1`);
                    } else {

                        urlParams.push(`${key}=${value}`);
                    }
                }
            });
            if (window.weaHistory) {
                window.weaHistory.push(`${route.excelView}?${urlParams.join('&')}`);
            }
    }

    deleteData = () => {
        ExcelAPI.deleteData({
            ...this.params,
        }).then((params) => {
            this.loading = false;
            message.success(getLabel('502230', '删除成功'));
            window.close();
        })
    }

    saveExcel = (exstore) => {
        this.checkInvalidValue();
        const source = this.dataSourceInstance.getSource();
        ExcelAPI.saveData({
            ...this.params,
            datas: JSON.stringify(source),
            // json: JSON.stringify(this.workbook.toJSON(false)),
            deletedRows: JSON.stringify(this.deletedRows),
        }).then((params) => {
            message.success(getLabel('502231', '保存成功'));
            // 刷新Excel展示页
            exstore.excelStore.reloadData();
        });
    }


    checkInvalidValue = () => {
        if (!this.workbook) {
            return true;
        }
        this.workbook.suspendPaint();
        const { sheets, ...json } = this.workbook.toJSON();
        const newSheets = {};
        const getSheet = ({ data, ...sheet }) => {
            const { dataTable, ...dataObj } = data;
            this.workbook.setActiveSheetIndex(sheet.index);
            const wksheet = this.workbook.getActiveSheet();
            const newDataTable = {};
            each(dataTable, (rowData, row) => {
                newDataTable[row] = {};
                each(rowData, (cellData, col) => {
                    const { style, ...restProps } = cellData;
                    if (typeof style === 'object' && style.cellType !== void 0) {
                        // 校验input类型数值是否合法
                        const cell = wksheet.getCell(Number(row), Number(col));
                        if (cell.text()) {
                            const cellType = cell.cellType();
                            if (cellType && cellType instanceof window.WeaInputCellType) {
                                const { fieldType: [htmlType, type, dbtype] } = cellType;
                                
                                const oldValue ='';
                                const newValue = cell.value();
                                if (type === 'int') {
                                    if (newValue) {
                
                                        const realValue = parseInt(newValue);
                                        if (isNaN(realValue)) {
                                            const formula = cell.formula();
                                            if(formula) {
                                                cell.formula('IFERROR(' + formula +',"")');
                                            } else {
                                                cell.value(oldValue);
                                            }
                                            //message.error(getLabel('502998', '请输入整数'));
                                            
                                        }
                                    }
                                } else if (type === 'float') {
                                    if (newValue) {
                                        const realValue = parseFloat(newValue);
                                        if (isNaN(realValue)) {
                                            const formula = cell.formula();
                                            if(formula) {
                                                cell.formula('IFERROR(' + formula +',"")');
                                            } else {
                                                cell.value(oldValue);
                                            }
                                            //message.error(getLabel('502999', '请输入浮点数'));
                                            
                                        }
                                    }
                                }
                            }
                            
                            
                        }

                    }
                })
            })
        }
        each(sheets, (sheet, sheetName) => {
            newSheets[sheetName] = getSheet(sheet);
        });
        this.workbook.resumePaint();
    }

    checkRequire = () => {
        // workbook不存在，意味着是自定义页面，不做必填校验
        if (!this.workbook) {
            return true;
        }
        const { sheets, ...json } = this.workbook.toJSON();
        const newSheets = {};
        let requireName;
        let requireLabel;
        const getSheet = ({ data, ...sheet }) => {
            const { dataTable, ...dataObj } = data;
            this.workbook.setActiveSheetIndex(sheet.index);
            const wksheet = this.workbook.getActiveSheet();
            const newDataTable = {};
            each(dataTable, (rowData, row) => {
                newDataTable[row] = {};
                if (requireName) {
                    return false;
                }
                each(rowData, (cellData, col) => {
                    const { style, ...restProps } = cellData;
                    if (typeof style === 'object' && style.cellType !== void 0 && style.cellType.viewAttr == 3) {
                        // 校验是否是必填
                        if (!wksheet.getCell(row, col).text()) {
                            const value = wksheet.getCell(row, col).value();
                            if(style.cellType.typeName==='WeaPicCellType' && value && value.toString()){

                            } else {
                                if (!requireName) {
                                    requireName = getCellName(Number(row), Number(col));
                                    requireLabel = style.cellType.label || "";
                                    this.requiredCellName = row + "@" + col;
    
                                    const requireSpan = wksheet.getSpan(Number(row), Number(col));

                                    this.workbook.suspendPaint();
                                    
                                    const requiredBoderStyle = new window.GC.Spread.Sheets.LineBorder('red', window.GC.Spread.Sheets.LineStyle.medium);

                                    if(!requireSpan) {
                                        const requireCell = wksheet.getCell(Number(row), Number(col));
                                        if (!this.requiredCellBoderStyle[this.requiredCellName]) {
                                            this.requiredCellBoderStyle[this.requiredCellName] = [
                                                requireCell.borderTop(),
                                                requireCell.borderLeft(),
                                                requireCell.borderBottom(),
                                                requireCell.borderRight()];
                                        }
                                        requireCell.setBorder(requiredBoderStyle, { all: true });
                                    } else {
                                        if (!this.requiredCellBoderStyle[this.requiredCellName]) {
                                            const cellsStyle = [];
                                            for(let r = requireSpan.row; r < requireSpan.row + requireSpan.rowCount; r++) {
                                                for(let c = requireSpan.col; c < requireSpan.col + requireSpan.colCount; c++) {
                                                    const requireCell = wksheet.getCell(r, c);
                                                    cellsStyle.push([
                                                        requireCell.borderTop(),
                                                        requireCell.borderLeft(),
                                                        requireCell.borderBottom(),
                                                        requireCell.borderRight()])
                                                }
                                            }
                                            this.requiredCellBoderStyle[this.requiredCellName] = cellsStyle;
                                        }
                                        const outCell = wksheet.getRange(requireSpan.row, requireSpan.col, requireSpan.rowCount, requireSpan.colCount);
                                        outCell.setBorder(requiredBoderStyle, {outline: true});
                                    }
                                    
                                    this.workbook.resumePaint();
                                }
    
                                // 移转到必填项
                                //wksheet.showCell(row, col);
    
                                //wksheet.setActiveCell(row, col);
                                return false;

                            }
                            
                        }

                    }
                })
            })
        }
        each(sheets, (sheet, sheetName) => {
            if (requireName) {
                return false;
            }
            newSheets[sheetName] = getSheet(sheet);
        });

        if (requireName) {
            message.fail("[" + requireLabel + ":" + requireName + "]" + getLabel('513480', '不能为空'));

            return false;
        } else {
            this.requiredCellName = "";
            return true;
        }
    }

    doBefore = () => {
        if (typeof (window.checkCustomize) == "function") {
            return window.checkCustomize();

        }
        return true;
    }

    getStyleValue = (style, styleName) => {
        const obj = style[styleName];
        if (styleName.startsWith("border")) {
            return new window.GC.Spread.Sheets.LineBorder(obj.color, obj.style);
        } else {
            return obj;
        }
    }
    calcAll = (flag = true, sheetName) => {
        if (flag) {
            if (sheetName) {
                this.func.forEach(fun => {
                    if (fun.key === sheetName) {
                        fun.action();
                    }
                });
                this.workbook.getSheetFromName(sheetName).tables.all().forEach(table => {
                    table.oldDataRange = { ...table.dataRange() };
                })
            } else {
                this.func.forEach(fun => {
                    fun.action();
                });
                this.workbook.sheets.forEach(sheet => {
                    sheet.tables.all().forEach(table => {
                        table.oldDataRange = { ...table.dataRange() };
                    })
                })
            }
        }
        this.workbook.sheets.forEach(sheet => {
            sheet.recalcAll(true);
        });
    }

    insertDetailRow = (records, index) => {
        const newRecords = [];
        if (index === -1) {
            newRecords.push({ detail_index: 1 });
        }
        records.forEach((record, recordIndex) => {
            if (recordIndex < index) {
                newRecords.push(record);
            } else if (recordIndex === index) {
                newRecords.push(record);
                newRecords.push({ detail_index: recordIndex + 2 });
            } else {
                newRecords.push({ ...record, detail_index: recordIndex + 2 });
            }
        });
        return newRecords;
    }
    removeDetailRow = (records, index) => {
        const newRecords = [];
        if (index === -1) {
            newRecords.push({ detail_index: 1 });
        }
        let detailIndex = 1;
        records.forEach((record, recordIndex) => {
            if (recordIndex < index) {
                newRecords.push({ ...record, detail_index: detailIndex++ });
            } else if (recordIndex > index) {
                newRecords.push({ ...record, detail_index: detailIndex++ });
            }
        });
        return newRecords;
    }

    mouseOverAnyWhere = (e) => {
        if (this.readonly) {
            return;
        }
    }
    getRangeRect = (sheet, row, col, rowCount, colCount) => {
        const { x, y } = sheet.getCellRect(row, col);
        const { x: x1, y: y1 } = sheet.getCellRect(row + rowCount, col + colCount);
        return {
            x, y,
            width: x1 - x,
            height: y1 - y
        };
    }
    showDetailBtns = (left, top, height, showDelete) => {
        if (this.cubeDetialBtns) {
            this.cubeDetialBtns.style.top = `${top}px`;
            this.cubeDetialBtns.style.display = 'block';
            this.cubeDetialBtns.style.height = `${height}px`;
            this.cubeDetialBtns.style.lineHeight = `${height}px`;
            this.cubeDetialBtns.style.left = `${left - 45}px`;
            this.showDetailDelete = showDelete;
        }
    }
    hideDetailBtns = () => {
        if (this.cubeDetialBtns) {
            this.cubeDetialBtns.style.display = 'none';
        }
    }
    @action
    reEnterCell = () => {
        const sheet = this.workbook.getActiveSheet();
        const sheetName = sheet.name();
        const col = sheet.getActiveColumnIndex();
        const row = sheet.getActiveRowIndex();
        this.enterCell({}, {
            col,
            row,
            sheet,
            sheetName
        });
    }

    tableToCell = () => {
        this.workbook.suspendPaint();
        const activeSheetIndex = this.workbook.getActiveSheetIndex();
        this.workbook.sheets.forEach(sheet => {
            this.workbook.setActiveSheet(sheet.name());
            this.activeSheetChange('', {
                newSheet: sheet
            });
            sheet.tables.all().forEach(table => {
                const { row, col, rowCount, colCount } = table.range();
                for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
                    for (let colIndex = 0; colIndex < colCount; colIndex++) {
                        const cell = sheet.getCell(row + rowIndex, col + colIndex);
                        const value = cell.text();
                        cell.cellType(new window.GC.Spread.Sheets.CellTypes.Base()).value(value);
                    }
                }

            })
        })
        this.workbook.setActiveSheetIndex(activeSheetIndex);
        this.workbook.resumePaint();
    }


    exportExcel = () => {
        const title = this.title;
        new Promise(resolve => {
            const excelIO = new window.GC.Spread.Excel.IO();
            // this.needCheck = false;
            // this.tableToCell();
            // this.needCheck = true;
            const activeIndex = this.workbook.getActiveSheetIndex();
            this.workbook.sheets.forEach((sheet, index) => {
                if(this.workbook.getSheet(index).visible()){
                    this.workbook.getTab().KD(index);
                }
            })
            this.workbook.setActiveSheetIndex(activeIndex);
            const { sheets, ...json } = this.workbook.toJSON();
            const newSheets = {};
            const getSheet = ({ data, tables, ...sheet }) => {
                const { dataTable, ...dataObj } = data;
                const wksheet = this.workbook.getSheet(sheet.index);
                const newDataTable = {};
                each(dataTable, (rowData, row) => {
                    newDataTable[row] = {};
                    each(rowData, (cellData, col) => {
                        const { style, ...restProps } = cellData;
                        const newStyle = style;
                        if (typeof style === 'object' && style.cellType !== void 0) {
                            const cellType = style.cellType.typeName;
                            delete newStyle.cellType;
                            delete newStyle.formatter;
                            restProps.value = wksheet.getCell(Number(row), Number(col)).text();
                            restProps.formula = '';
                            newDataTable[row][col] = {
                                ...restProps,
                                style: newStyle
                            }
                        } else if (wksheet.getCell(Number(row), Number(col)).text()) {
                            restProps.value = wksheet.getCell(Number(row), Number(col)).text();
                            restProps.formula = '';
                            newDataTable[row][col] = {
                                ...restProps,
                                style: newStyle
                            }
                        } else {
                            newDataTable[row][col] = cellData;
                        }
                    })
                   
                })
                if (tables) {
                    tables.forEach(table => {
                        const { row, col, rowCount, colCount } = table;

                        if (!newDataTable[row]) {
                            newDataTable[row] = {};
                        }
                        for (let i = 0; i < colCount; i++) {
                            if (newDataTable[row][col + i]) {
                                continue;
                            }
                            const cellData = wksheet.getCell(Number(row), Number(col + i));
                            const { style, ...restProps } = cellData;
                            // let newStyle = style;
                            // if (typeof style === 'object' && style.cellType !== void 0) {

                            //     delete newStyle.formatter;
                            //     delete newStyle.cellType;

                            //     restProps.value = cellData.text();
                            //     newDataTable[row][(col+i)] = {
                            //         ...restProps,
                            //     style: newStyle                         
                            //     }
                            //     console.log(restProps.value,"test");
                            // } else 
                            if (cellData.text()) {
                                restProps.value = cellData.text();
                                restProps.formula = '';

                                let newStyle = {}
                                newStyle.textIndent = cellData.textIndent();
                                newStyle.backgroundImageLayout = cellData.backgroundImageLayout();
                                newStyle.backgroundImage = cellData.backgroundImage();
                                newStyle._oldTag = cellData.tag();
                                newStyle.backColor = cellData.backColor();
                                newStyle.foreColor = cellData.foreColor();
                                newStyle.borderBottom = cellData.borderBottom();
                                newStyle.borderLeft = cellData.borderLeft();
                                newStyle.borderRight = cellData.borderRight();
                                newStyle.borderTop = cellData.borderTop();
                                newStyle.font = cellData.font();
                                newStyle.hAlign = cellData.hAlign();
                                newStyle.height = cellData.height();
                                newStyle.vAlign = cellData.vAlign();
                                newDataTable[row][(col + i)] = {
                                    ...restProps,
                                    style: newStyle

                                }

                            }

                        }
                    })

                }
                return {
                    ...sheet,
                    data: {
                        ...dataObj,
                        dataTable: newDataTable
                    },
                    tables: []
                }
            }

            each(sheets, (sheet, sheetName) => {
                newSheets[sheetName] = getSheet(sheet);
            });
            const newJson = {
                ...json,
                newTabVisible: true,
                sheets: newSheets
            }
            excelIO.save(newJson, (blob) => {
                window.saveAs(blob, `${title}.xlsx`);
                // this.init(this.params);
                resolve();
            }, function (e) {
                if (!!(window.console && window.console.log)) {
                    window.console.log(e);
                }
                // this.init(this.params);
                resolve();
            });
        })
    }

    exportExcel4Upload = () => {
        const title = this.title;
        return new Promise(resolve => {
            const excelIO = new window.GC.Spread.Excel.IO();
            // this.needCheck = false;
            // this.tableToCell();
            // this.needCheck = true;
            const { sheets, ...json } = this.workbook.toJSON();
            const newSheets = {};
            const activeIndex = this.workbook.getActiveSheetIndex();
            const getSheet = ({ data, ...sheet }) => {
                const { dataTable, ...dataObj } = data;
                this.workbook.setActiveSheetIndex(sheet.index);
                const wksheet = this.workbook.getActiveSheet();
                const newDataTable = {};
                each(dataTable, (rowData, row) => {
                    newDataTable[row] = {};
                    each(rowData, (cellData, col) => {
                        const { style, ...restProps } = cellData;
                        const newStyle = style;
                        if (typeof style === 'object' && style.cellType !== void 0) {
                            delete newStyle.cellType;
                            delete newStyle.formatter;
                            restProps.value = wksheet.getCell(row, col).text();
                        }
                        newDataTable[row][col] = {
                            ...restProps,
                            style: newStyle
                        }
                    })
                })
                return {
                    ...sheet,
                    data: {
                        ...dataObj,
                        dataTable: newDataTable
                    }
                }
            }
            each(sheets, (sheet, sheetName) => {
                newSheets[sheetName] = getSheet(sheet);
            });
            const newJson = {
                ...json,
                newTabVisible: true,
                sheets: newSheets
            }
            this.workbook.setActiveSheetIndex(activeIndex);
            excelIO.save(newJson, (blob) => {
                window.saveAs(blob, `${title}.xlsx`);
                // this.init(this.params);
                resolve();
            }, function (e) {
                if (!!(window.console && window.console.log)) {
                    window.console.log(e);
                }
                // this.init(this.params);
                resolve();
            });
        })
    }

    // exportExcelTemplate = (title = this.title) => {
    //     //API.template(this.params).then(this.downTemplate)
    //     return new Promise(resolve => {
    //         const excelIO = new window.GC.Spread.Excel.IO();
    //         this.tableToCell();
    //         console.log(this.workbook.toJSON());
    //         excelIO.save(this.workbook.toJSON(), (blob) => {
    //             saveAs(blob, `${this.title}.xlsx`);
    //             //this.init(this.params);
    //             resolve();
    //         }, function (e) {
    //             if (!!(window.console && window.console.log)) {
    //                 window.console.log(e);
    //             }
    //             resolve();
    //         });
    //     });
    // }

    downTemplate = (template) => {
        let fileName = template.fileName || template.name;
        if (fileName.substr(-5, 5) !== '.xlsx') {
            fileName += '.xlsx';
        }
        return new Promise(resolve => {
            const excelIO = new window.GC.Spread.Excel.IO();
            excelIO.save(template.json, (blob) => {
                window.saveAs(blob, fileName);
                resolve();
            }, function (e) {
                if (!!(window.console && window.console.log)) {
                    window.console.log(e);
                }
            });
            resolve();
        });
    }

    getShowListDatas = (oldFields, newFields) => {
        return new Promise(resolve => {
            const [file] = newFields;
            if (file) {
                const fileInstance = file.getNative();
                // this.loadFile(fileInstance, fileInstance.name.replace('.xlsx', ''));
                // this.setVisible(false);
                this.uploadName = fileInstance.name;
                this.fileInstance = fileInstance;
            }
            resolve();
        }, function (e) {
            if (!!(window.console && window.console.log)) {
                window.console.log(e);
            }
        });
    }

    loadFile = () => {
        if(this.uploadName) {
            const file = this.fileInstance;
            const name = this.uploadName.replace('.xlsx', '');
            const excelIO = new window.GC.Spread.Excel.IO();
            excelIO.open(
                file,
                json => {
                    this.showLoadPage({
                        json: json,
                        labels: {},
                        fieldName: {},
                        name
                    });
                },
                (error) => {
                    message.fail(error);
                    this.loading = false;
                }
            );
        }
        
    }

    /**
     * 初始化加载时渲染图片
     */
    loadPictures = () => {
        const activeIndex = this.workbook.getActiveSheetIndex();
        this.workbook.sheets.forEach((sheet, index) => {
            if(this.workbook.getSheet(index).visible()){
                this.workbook.getTab().KD(index);
            }
        })
        this.workbook.setActiveSheetIndex(activeIndex);
        this.workbook.suspendPaint();
        const sheets = this.workbook.toJSON().sheets;
        this.workbook.sheets.forEach((sheet, index) => {
            const sheetName = sheet.name();
            const sheetObj = sheets[sheetName] || {};
            const { tables = [], data: { dataTable = {} } = {} } = sheetObj;
            //遍历处理图片字段
            each(dataTable, (rowData, rowIndex) => {
                each(rowData, (cellData, colIndex) => {
                    const { style = {} } = cellData;
                    const { cellType } = style;
                    if (cellType && cellType.typeName === 'WeaPicCellType') {
                        const row = Number(rowIndex);
                        const col = Number(colIndex);
                        const cellObj = sheet.getCell(row, col);
                        const cellTypeObj = cellObj.cellType();
                        const {sheetArea} = cellObj
                        const {showPic} = cellTypeObj;
                        const fileList = cellObj.value();
                        if (fileList && fileList.length > 0) {
                            showPic(fileList, { row: row, col: col, sheet: sheet, sheetArea: sheetArea });
                        }
                    }
                });
            });
        });
        this.workbook.resumePaint();
    }

    /**
     * 导入时处理图片字段
     */
    bindPictures = (sheets) => {
        this.workbook.suspendPaint();
        this.workbook.sheets.forEach(sheet => {
            const name = sheet.name();
            const {floatingObjects} = sheets[name];
            if(floatingObjects){
                floatingObjects.map(floatingObject => {
                    const {name,x,y,startRow,startColumn,width,height,src,borderStyle,borderWidth}= floatingObject;
                    const cellObj = sheet.getCell(startRow, startColumn);
                    if(cellObj){
                        const cellTypeObj = cellObj.cellType();
                        const { sheetArea } = cellObj;
                        if(cellTypeObj instanceof window.WeaPicCellType){
                            const { imageHeight,imageWidth,browserInstance } = cellTypeObj;
                            let name = 'f' + String(startColumn) + String(startColumn);
                            let picture = sheet.pictures.get(name);
                            if(!picture){
                                picture = sheet.pictures.add(name);
                            }
                            picture.src(src);
                            picture.startRow(startRow);
                            picture.startColumn(startColumn);
                            picture.startRowOffset(0);
                            picture.startColumnOffset(0);
                            picture.endRow(startRow + 1);
                            picture.endColumn(startColumn + 1);
                            picture.endRowOffset(0);
                            picture.endColumnOffset(-50);
                            sheet.setRowHeight(startRow, imageHeight, sheetArea);
                            sheet.setColumnWidth(startColumn, Number(imageWidth) + 50, sheetArea);
                        }
                    }

                   
                })
            }
            this.calcAll();
        });
        this.workbook.resumePaint();
    }

    showLoadPage = (page) => {
        const json = page.json;
        const sheets = json.sheets;
        
        this.pgid = Number((Date.now() + Math.random()).toString()
        .replace('.', Math.round(Math.random() * 18))).toString(16);
        this.uploadPids.push(this.pgid);
        this.pgvisible = true;
        this.progressInterval = setInterval(() => {
            this.getProgress()
        }, 200);
        // ExcelAPI.uploadData({
        //     dataJson: JSON.stringify(sheets),
        //     //sheetsJson: JSON.stringify(this.workbook.toJSON(false)),
        //     sheetsJson:JSON.stringify(this.orgJson),
        //     pgid:this.pgid
        // }).then
        const base64DataJson = Base64.encode(JSON.stringify(sheets));
        const base64SheetsJson = Base64.encode(JSON.stringify(this.workbook.toJSON(false)));
        Tools.callApi('/api/edc/excel/uploadData', 'POST', {
             //...p, ...(this.excelStore.downloadCondition || {})
            dataJson: base64DataJson,
            sheetsJson: base64SheetsJson,
            //sheetsJson:JSON.stringify(this.orgJson),
            pgid:this.pgid
            }).then((res) => {
                
                const status = res.api_status;
                if(!status) {
                    message.fail(getLabel('514578','导入数据失败'));
                    return;
                }
                const ds = res.data;
                // 关闭循环获取状态
                clearInterval(this.progressInterval);
                this.progress = 100;
                this.pgvisible = false;
                this.uploadName = undefined;
                this.fileInstance = undefined;
                this.progress = 0;
                
                if(this.uploadPids.indexOf(this.pgid) == -1) {
                    return
                }
                this.setVisible(false);
                this.pgid = undefined;
                this.bindDatasource(ds);
                // this.initFieldAssign();
                this.triggerFieldAssign(true);
                const sheets = this.workbook.toJSON().sheets;
                const activeIndex = this.workbook.getActiveSheetIndex();
                this.workbook.sheets.forEach((sheet, index) => {
                    if(this.workbook.getSheet(index).visible()){
                        this.workbook.getTab().KD(index);
                    }
                    const sheetName = sheet.name();
                    const sheetObj = sheets[sheetName] || {};
                    const { data: { dataTable = {} } = {} } = sheetObj;
                    //遍历处理图片字段
                    each(dataTable, (rowData, rowIndex) => {
                        each(rowData, (cellData, colIndex) => {
                            const { style = {} } = cellData;
                            const { cellType } = style;
                            if (cellType && cellType.typeName === 'WeaPicCellType') {
                                sheet.suspendPaint();
                                sheet.pictures.clear();
                                const row = Number(rowIndex);
                                const col = Number(colIndex);
                                //做渲染操作
                                const cellObj = sheet.getCell(row, col);
                                const cellTypeObj = cellObj.cellType();
                                const { sheetArea } = cellObj
                                const { showPic } = cellTypeObj;
                                const fileList = cellObj.value();
                                if (fileList && fileList.length > 0) {
                                    showPic(fileList, { row: row, col: col, sheet: sheet, sheetArea: sheetArea });
                                }
                                sheet.resumePaint();
                            }
                        });
                    });
                })
                this.workbook.setActiveSheetIndex(activeIndex);
                message.success(getLabel('514579','上传数据成功'))
        }).catch((e) => {
            // 关闭循环获取状态
            clearInterval(this.progressInterval);
            message.fail(getLabel('514578','导入数据失败'));
            this.uploadName = undefined;
            this.fileInstance = undefined;
            this.progress = 0;
            this.pgvisible = false;
            console.log(e);
          });
        return;

    }

    getProgress = () => {
        ExcelAPI.getProgress(this.pgid).then(data => {
            
            const persent = data.progress;
            if(persent || persent == 0) {
                this.progress = persent;
                if (persent != 100) {
                    console.log(persent,"persent");
                    if(!this.pgvisible) {
                        this.progress = 0;
                        clearInterval(this.progressInterval);
                    }
                } else {
                    clearInterval(this.progressInterval);
                    this.finishProgress();
                }
            }
        })
    }
    finishProgress = () => {
        ExcelAPI.finishProgress(this.pgid);
    }

    @action toggle = () => {
        this.autoSaveDatasvisible = !this.autoSaveDatasvisible;
    }

    bindDatasource = (ds,wk) => {
        const dataSource = window.dataSourceInstance = this.dataSourceInstance = new window.GC.Spread.Sheets.Bindings.CellBindingSource(ds);
        if(wk) {
            this.workbook.fromJSON(wk,false);

            if(ds) {
                // sheet
                for(let key in ds) {
                    // sheet中的值
                    const pathMap = ds[key]
                    if(pathMap)
                    for(let pathKey in pathMap) {
                        if(pathKey.startsWith('custom_')) {
                            
                            const customMap = pathMap[pathKey];
                            
                            let tmpCurrentKey = 0;
                            if(customMap){
                                for(let currentT in customMap) {
                                    if(currentT.startsWith('t')) {
                                        let tt = Number(currentT.substring(1));
                                        if(tt > tmpCurrentKey) {
                                            tmpCurrentKey = tt;
                                        }
                                    }
                                }
                                
                            }
                            if(pathKey.indexOf('h') > -1) {
                                const name = key + "." + pathKey.substring(0,pathKey.length-1);
                                console.log(this.customExpandCurrent,'customExpandCurrent');
                                this.customExpandCurrent[name] = tmpCurrentKey;
                                console.log(this.customExpandCurrent);
                            }else {
                                const name = key + "." + pathKey;
                                console.log(this.customBindingCurrentT,'customBindingCurrentT');
                                this.customBindingCurrentT[name] = tmpCurrentKey;
                                console.log(this.customBindingCurrentT);
                            }
                            
                        }
                        
                    }
                }
            }
        }
        this.workbook.suspendPaint();
        this.workbook.sheets.forEach(sheet => {
            sheet.setDataSource(dataSource);
            this.calcAll();
            this.changeSelectTypeValue();
            try{
            if (window.excel.initCheckValue && typeof (window.excel.initCheckValue()) == "function") {
                
                window.excel.initCheckValue();
                
            }
        } catch(e) {
            console.log(e);
            //message.error("代码块方法（initCheckValue）执行有错误")
        }
        });
        this.workbook.resumePaint();

        this.setDetailTableRowHeight();
        // 由于自定义明细表的数据顺序不能保证，先不使用这种保存方式
        // this.bindingVersionData = true;
        // const workbook = new window.GC.Spread.Sheets.Workbook();
        // this.workbook.fromJSON(workbook.toJSON(), false);
        // this.workbook.unbindAll();
        // console.log(ds,"ds")
        // if(ds) {
        //     // sheet
        //     for(let key in ds) {
        //         // sheet中的值
        //         const pathMap = ds[key]
        //         if(pathMap)
        //         for(let pathKey in pathMap) {
        //             if(pathKey.startsWith('custom') && pathKey.indexOf("_") == -1) {
        //                 console.log(pathKey, pathMap[pathKey])
        //             }
                    
        //         }
        //         console.log(key,ds[key])
        //     }
        // }
        // this.versionDatasource = ds;
        // this.init(this.params);
    }

    valueCheck = (cellType, newValue) => {
        if (cellType instanceof window.WeaInputCellType) {
            const { fieldType: [htmlType, type, dbtype] } = cellType;
            if (type === 'text') {
                const length = parseInt(dbtype);
                if (this.GetLength(`${newValue}`) > length) {

                    message.fail(`${getLabel(502997, '长度不能超过') + length}`);
                    return "";
                } else {
                    return newValue;
                }

            } else if (type === 'int') {
                const realValue = parseInt(newValue);
                if (isNaN(realValue)) {
                    message.fail(getLabel(502998, `请输入整数`));
                    return "";
                } else {
                    return realValue;
                }

            } else if (type === 'float') {
                const realValue = parseFloat(newValue);
                const length = parseInt(dbtype);
                if (isNaN(realValue)) {
                    message.fail(getLabel(502999, `请输入浮点数`));
                    return "";
                } else {
                    return realValue.toFixed(length);
                }

            }
        }
    }
    GetLength = (str) => {
        ///<summary>获得字符串实际长度，中文2，英文1</summary>
        ///<param name="str">要获得长度的字符串</param>
        var realLength = 0, len = str.length, charCode = -1;
        for (var i = 0; i < len; i++) {
            charCode = str.charCodeAt(i);
            if (charCode >= 0 && charCode <= 128)
                realLength += 1;
            else
                realLength += 2;
        }
        return realLength;
    };
    @action setVisible = (bool) => {
        this.visible = bool;
        this.pgvisible = false;
        this.uploadName = undefined;
        this.fileInstance = undefined;
        this.pgid = undefined;
        this.uploadPids = [];
    }

    @action getExcelFields() {
        if (this.workbook) {
            const workbook = this.workbook.toJSON();
            const { sheets } = workbook;
            if (sheets) {
                each(sheets, (sheet) => {
                    const { data, tables } = sheet;
                    if (tables) {
                        tables.forEach(table => {
                            const { bindingPath, columns, name } = table;
                            const nameArr = name.split('detail');
                            if (nameArr && nameArr[1]) {
                                if (columns) {
                                    columns.forEach(column => {
                                        this.detailFields.push(`${bindingPath}.${column.dataField}`);
                                    });
                                }
                            }
                        });
                    }

                    if (data) {
                        const { dataTable } = data;
                        if (dataTable) {
                            each(dataTable, (o) => {
                                each(o, (obj) => {
                                    const { bindingPath } = obj;
                                    if (bindingPath) {
                                        this.mainFields.push(bindingPath);
                                    }
                                });
                            });
                        }
                    }
                });
            }
        }
    }

    /**
     * 获取字段数据的值，为字符串取本身，为数组取value拼接
     */
    getFieldValue = (value) => {
        let returnValue = "";
        if (value && Array.isArray(value)) {
            let idArr = new Array();
            value.forEach((o) => {
                idArr.push(o.id);
            });
            returnValue = idArr.join(",");
        } else {
            returnValue = value;
        }
        return returnValue;
    }

    /**
     * 根据字段名判断sql中是否存在该字段
     */
    isExistField(sql, field) {
        const key = `\\$${field}\\$`;
        const regExp = new RegExp(key, 'g');
        return (sql.search(regExp) != -1) ? true : false;
    }

    /**
     * 根据字段集合获取fieldAssignList
     */
    getFieldAssignList = (changeFieldList) => {
        let fieldAssignList = [];
        //去重合并
        changeFieldList.forEach(c => {
            const { changeField, detailIndex } = c;
            this.fieldAssignList.forEach((f) => {
                let sql = "";
                const conditionInfoObj = JSON.parse(f.conditionInfo);
                const { conditiontype, conditionsql, conditionsql2 } = conditionInfoObj;
                if (conditiontype === "1") {
                    sql = conditionsql;
                } else if (conditiontype === "2") {
                    sql = conditionsql2;
                }
                if (f.type == '1' && this.isExistField(sql, changeField)) {
                    if (detailIndex != null && typeof detailIndex != 'undefined') {
                        fieldAssignList.push({ ...f, detailIndex: detailIndex });
                    } else {
                        fieldAssignList.push(f);
                    }
                }
            })

        });
        var result = [];
        var obj = {};
        for (let i = 0; i < fieldAssignList.length; i++) {
            const fa = fieldAssignList[i];
            if (!obj[fa.id]) {
                result.push({
                    ...fa,
                    detailIndex: fa.detailIndex != null && typeof fa.detailIndex != 'undefined' ? [fa.detailIndex] : []
                });
                obj[fa.id] = fa;
            } else {
                for (let j = 0; j < result.length; j++) {
                    const r = result[j];
                    if (r.id == fa.id) {
                        if (fa.detailIndex != null && typeof fa.detailIndex != 'undefined') {
                            r.detailIndex.push(fa.detailIndex);
                        }
                        r.detailIndex = Array.from(new Set(r.detailIndex));
                        break;
                    }
                }
            }
        }
        this.triggerFieldAssign(false, result);
    }

    /**
     * 初始化加载时字段赋值条件存在值，则主动触发联动，如固定解析、公式赋值等情形
     * 触发字段赋值逻辑,传入字段赋值配置的集合fieldAssignList
     * 1.主表联动多行明细（条件不存在明细字段，赋值字段存在明细字段）；2.主表联动主表/或单元格（条件不存在明细字段，赋值字段不存在明细字段）；3.明细联动明细行（条件存在明细字段--单行明细触发/  多行明细触发联动多行/主表字段触发联动多行--注意去重 传入明细行条件的集合，包含索引+主表字段）
     * @param fieldAssignList 
     */
    @action triggerFieldAssign = (isInit, fieldAssignList) => {
        // this.getFieldInfoMap();
        // let changeFieldList = [];
        //fieldAssignList，假如是明细触发明细，单行明细触发给这个集合里面该条记录加上该条触发索引和明细字段数值，不加则默认取全部明细表值遍历做请求
        const list = isInit ? this.fieldAssignList : fieldAssignList;
        this.getExcelFields();
        //取所有类型为满足特定条件赋值type=1的字段赋值配置记录遍历
        list.filter(f => f.type == '1').map(fa => {
            const Base64 = Base64;
            let hasDetailField = false;
            let hasMainField = false;
            let detailTable = "";
            let sql = "";//条件中的sql
            const { id, conditionInfo, detailIndex, triggerType } = fa;
            const conditionInfoObj = JSON.parse(conditionInfo);
            const { conditiontype, conditionsql, conditionsql2 } = conditionInfoObj;
            if (conditiontype === "1") {
                sql = conditionsql;
            } else if (conditiontype === "2") {
                sql = conditionsql2;
            }
            //条件中包含明细表字段
            this.detailFields.forEach(field => {
                if (this.isExistField(sql, field)) {
                    const paths = field.split('.');
                    if (paths.length >= 3) {
                        detailTable = paths[0] + '.' + paths[1];//明细联动明细时的明细表名称
                    }
                    hasDetailField = true;
                    return false;
                }
            });
            //条件中包含主表字段
            this.mainFields.forEach(field => {
                if (this.isExistField(sql, field)) {
                    hasMainField = true;
                    return false;
                }
            });

            if (hasMainField && !hasDetailField) {
                let sqlparam = {};
                let isTrigger = true;//是否触发联动
                //条件纯主表字段,如果有某个条件字段值为空则不触发，假如都有值则拼好sql请求接口赋值
                this.mainFields.forEach(field => {
                    if (this.isExistField(sql, field)) {
                        const value = this.dataSourceInstance.getValue(field);
                        if ((value == null || typeof value == 'undefined') && typeof value != "boolean") {
                            sqlparam[field] = '';
                        } else {
                            sqlparam[field] = this.getFieldValue(value);
                        }
                    }
                });
                if (isTrigger) {
                    let dataParams = {
                        ...this.params,
                        isDetailField: "0",
                        sqls: JSON.stringify({ id: id, sqlparam: sqlparam, sql: Base64.encode(sql) })
                    };
                    API.getFieldAssignData(dataParams).then((result) => {
                        if (result) {
                            this.getFieldInfoMap();
                            // this.workbook.suspendPaint();
                            const mainfield = result.mainfield;
                            if (this.mainFieldInfoMap) {
                                each(this.mainFieldInfoMap, (mainMapSheet, sheetname) => {
                                    const mainsheet = mainfield[sheetname];
                                    if (mainsheet) {
                                        each(mainMapSheet, (fieldindex, fieldname) => {
                                            const value = mainsheet[fieldname];
                                            const { row, col } = fieldindex;
                                            const sheet = this.workbook.getSheetFromName(sheetname);
                                            if (typeof value != 'undefined') {
                                                sheet.suspendPaint();
                                                sheet.getCell(Number(row), Number(col)).value(value);
                                                sheet.resumePaint();
                                            }
                                        });
                                    }
                                });
                            }

                            const detailfield = result.detailfield;
                            if (this.detailFieldInfoMap) {
                                each(this.detailFieldInfoMap, (detailMapSheet, sheetname) => {
                                    const detailsheet = detailfield[sheetname];
                                    const sheet = this.workbook.getSheetFromName(sheetname);
                                    if (detailsheet) {
                                        //有序遍历明细表，从下到上
                                        for (let i = 0, len = detailMapSheet.length; i < len; i++) {
                                            sheet.suspendPaint();
                                            const { tablename, detailname, dataCount, fieldindex, row } = detailMapSheet[i];
                                            const detail = detailsheet[detailname];
                                            if (detail && fieldindex) {
                                                //初始化明细表行
                                                let lengthArr = [0];
                                                for (let key in detail) {
                                                    lengthArr.push(detail[key].length);
                                                }
                                                const valueCount = Math.max(...lengthArr);
                                                const bindingPath = sheetname + '.' + detailname;
                                                const records = this.dataSourceInstance.getValue(bindingPath);
                                                let totalCount = valueCount;
                                                const rowCount = this.getRowCount(sheetname, bindingPath);
                                                let newValue = [];
                                                let defaultCount = 0;
                                                if (triggerType === '0') {
                                                    //根据配置的明细表加载方式扩充明细行 0:只添加明细 1:先删除再添加
                                                    totalCount = dataCount + valueCount;
                                                    newValue = records;
                                                }
                                                if (totalCount >= rowCount) {
                                                    for (let j = 0; j < totalCount; j++) {
                                                        if (j < dataCount && triggerType === '0')
                                                            continue;
                                                        newValue.push({ detail_index: j + 1 });
                                                    }
                                                    defaultCount = totalCount;
                                                } else {
                                                    for (let j = 0; j < rowCount; j++) {
                                                        newValue.push({ detail_index: j + 1 });
                                                    }
                                                    defaultCount = rowCount;
                                                }
                                                this.dataSourceInstance.setValue(bindingPath, newValue);
                                                const table = sheet.tables.findByName(tablename);
                                                table.bindingPath(bindingPath);
                                                this.calcAll(true, sheetname);
                                                let startRow = 0;
                                                for (let key in fieldindex) {
                                                    const { row } = fieldindex[key];
                                                    startRow = row;
                                                    if (triggerType === '0') {
                                                        startRow = dataCount + row;
                                                    }
                                                    this.setUserinfo2newRow(table, startRow, defaultCount);
                                                    break;
                                                }

                                                each(fieldindex, (o, fieldname) => {
                                                    const value = detail[fieldname];//明细表字段数组
                                                    const { row, col } = o;//明细表初始行列
                                                    if (typeof value != 'undefined' && value.length > 0) {
                                                        for (let i = 0; i < value.length; i++) {
                                                            sheet.getCell(Number(startRow) + i, Number(col)).value(value[i]);
                                                        }
                                                    }
                                                });
                                                this.setDetailTableRowHeight();
                                            }
                                            sheet.resumePaint();
                                        }
                                    }
                                });
                            }
                            // this.workbook.resumePaint();
                        }
                    });
                }

            } else if (hasDetailField) {
                //条件包含明细表字段
                let sqlparam = {};
                let isTrigger = true
                if (hasMainField) {
                    //先遍历主表条件，假如主表有条件字段为空，则不触发
                    this.mainFields.forEach(field => {
                        if (this.isExistField(sql, field)) {
                            const value = this.dataSourceInstance.getValue(field);
                            if ((value == null || typeof value == 'undefined') && typeof value != "boolean") {
                                isTrigger = false;
                                return false;
                            } else {
                                sqlparam[field] = this.getFieldValue(value);
                            }
                        }
                    })
                }

                if (isTrigger) {
                    let sqlparams = [];
                    //再遍历明细表
                    const records = this.dataSourceInstance.getValue(detailTable);
                    let indexArr = [];
                    if (!detailIndex) {
                        for (let i = 0; i < records.length; i++) {
                            indexArr.push(i);
                        }
                    } else {
                        if (detailIndex.length == 0) {
                            for (let i = 0; i < records.length; i++) {
                                indexArr.push(i);
                            }
                        } else {
                            indexArr = detailIndex;
                        }
                    }
                    // if (detailIndex) {
                    indexArr.forEach(index => {
                        const record = records[index];
                        console.log(records, record, index);
                        let detailsqlparam = { ...sqlparam };
                        let isAddDetailsql = true;
                        this.detailFields.forEach(field => {
                            //取当前行的数据
                            const paths = field.split('.');
                            let dfield = "";
                            if (paths.length >= 3) {
                                dfield = paths[2];
                            }
                            if (this.isExistField(sql, field)) {
                                const value = record[dfield];
                                if ((value == null || typeof value == 'undefined') && typeof value != "boolean") {
                                    isAddDetailsql = false;
                                    return false;
                                } else {
                                    detailsqlparam[field] = this.getFieldValue(value);
                                }
                            }
                        });
                        if (isAddDetailsql) {
                            sqlparams.push({ detailsqlparam: detailsqlparam, index: index });
                        }
                    });
                    // }

                    if (sqlparams.length > 0) {
                        let dataParams = {
                            ...this.params,
                            isDetailField: "1",
                            isMulti: "1",
                            sqls: JSON.stringify({ id: id, sqlparam: sqlparams, sql: Base64.encode(sql) })
                        };
                        API.getFieldAssignData(dataParams).then((result) => {
                            if (result) {
                                this.getFieldInfoMap();
                                this.workbook.suspendPaint();
                                const detailfield = result.detailfield;
                                if (this.detailFieldInfoMap) {
                                    each(this.detailFieldInfoMap, (detailMapSheet, sheetname) => {
                                        const detailsheet = detailfield[sheetname];
                                        const sheet = this.workbook.getSheetFromName(sheetname);
                                        if (detailsheet) {
                                            //有序遍历明细表，从下到上
                                            for (let i = 0, len = detailMapSheet.length; i < len; i++) {
                                                const { detailname, fieldindex } = detailMapSheet[i];
                                                const detail = detailsheet[detailname];
                                                if (detail && fieldindex) {
                                                    each(fieldindex, (o, fieldname) => {
                                                        const value = detail[fieldname];//明细表字段数组
                                                        const { row, col } = o;//明细表初始行列
                                                        if (typeof value != 'undefined' && value.length > 0) {
                                                            let startRow = row;
                                                            for (let i = 0; i < value.length; i++) {
                                                                const { v, index } = value[i];
                                                                sheet.getCell(Number(startRow) + Number(index), Number(col)).value(v);
                                                            }

                                                        }
                                                    });
                                                }
                                            }
                                        }
                                    });
                                }
                                this.workbook.resumePaint();
                            }
                        });
                    }
                }
            }

        });
        this.changeFieldList = [];
    }

    /**
     * 根据bindingPath获取设计行数
     */
    getRowCount = (sheetname, bindingPath) => {
        let rowCount = 0;
        const sheet = toJS(this.rowControl)[sheetname];
        if (sheet.length > 0 && Array.isArray(sheet)) {
            // 终止for循环，使用break
            for (let i = 0; i < sheet.length; i++) {
                if (bindingPath === sheet[i].bindingPath) {
                    rowCount = Number(sheet[i].rowCount);
                    break;
                }
            }
        }
        return rowCount;
    }

    /**
     * 获取明细表数据绑定名
     */
    getDetailName = (bindingPath) => {
        const paths = bindingPath.split('.');
        let detailname = "";
        if (paths.length >= 2) {
            detailname = paths[1];
        }
        return detailname;
    }

    /**
     * 获取有效行数
     */
    getDataCount = (bindingPath) => {
        const records = this.dataSourceInstance.getValue(bindingPath);
        let oldNum = 0;
        records.forEach((record) => {
            let isAdd = false;
            for (let [key, value] of Object.entries(record)) {
                if (key !== 'detail_index') {
                    if (value != null || typeof value != 'undefined') {
                        isAdd = true;
                        break;
                    }
                }
            }
            //明细表某行有某个字段不为空就计入初始行数，这个判断要在明细表加载前执行
            if (isAdd) {
                //遍历表格数据假如该行有数据则计入初始行数
                oldNum++;
            }
        });
        return oldNum;
    }

    /**
     * 倒序比较
     */
    compare = (property) => {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            return value2 - value1;
        }
    }

    /**
     * 获取页面上字段和行列的对应关系，先对主表进行赋值，给明细表赋值时从下往上
     */
    getFieldInfoMap = () => {
        this.workbook.sheets.forEach(sheet => {
            const sheetname = sheet.name();
            let detailArr = [];
            //明细表
            sheet.tables.all().forEach(table => {
                const bindingPath = table.bindingPath();
                const tablename = table.name();
                if (bindingPath) {
                    
                    const detailname = this.getDetailName(bindingPath);
                    const dataCount = this.getDataCount(bindingPath);
                    const { row, colCount, col } = table.dataRange();
                    let fieldindex = {};
                    for (let i = 0; i < colCount; i++) {
                        const cell = sheet.getCell(Number(row), Number(col + i));
                        const cellType = cell.cellType();
                        if (cellType && cellType.fieldType) {
                            const fieldname = table.getColumnDataField(i);
                            fieldindex[fieldname] = { row: row, col: col + i };
                        }
                    }
                    detailArr.push({ tablename: tablename, detailname: detailname, dataCount: dataCount, row: row, fieldindex: fieldindex });
                }
            });
            //按行排序从下往上
            detailArr.sort(this.compare('row'))
            this.detailFieldInfoMap[sheetname] = detailArr;
            //主表
            let fieldindex = {};
            const { data } = sheet.toJSON();
            if (data) {
                const { dataTable } = data;
                if (dataTable) {
                    each(dataTable, (o, rowIndex) => {
                        each(o, (obj, colIndex) => {
                            const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
                            if (bindingPath) {
                                const cell = sheet.getCell(Number(rowIndex), Number(colIndex));
                                const cellType = cell.cellType();
                                if (cellType && cellType.fieldType) {
                                    const fieldname = this.getMainFieldName(cell.bindingPath());
                                    fieldindex[fieldname] = { row: rowIndex, col: colIndex };

                                }
                            }
                        });
                    });
                    this.mainFieldInfoMap[sheetname] = fieldindex;
                }
            }
        });
    }

    isObjectValueEqual = (a, b, checknull) => {
        if(a && b) {

        } 
        // else if(checknull){
        //     // 外部传过来时判断
        //     return false;
        // } 
        else {
            if(a == b) {
                return true;
            } else {
                return false;
            }
        }
        var aProps = Object.getOwnPropertyNames(a);
        var bProps = Object.getOwnPropertyNames(b);
         if (aProps.length != bProps.length) {
              return false;
         }
         for (var i = 0; i < aProps.length; i++) {
           var propName = aProps[i]
   
           var propA = a[propName]
           var propB = b[propName]
           if ((typeof (propA) === 'object')) {
             if (this.isObjectValueEqual(propA, propB)) {
                 return true
               } else {
                 return false
               }
           } else if (propA != propB) {
             return false
           } else { }
         }
       return true
       }

       setSameHeight = (sheet, curRow, downExpandspanRowCount) => {
           for(let i = 0 ; i < downExpandspanRowCount ; i++) {
               sheet.setRowHeight(curRow + downExpandspanRowCount + i, sheet.getRowHeight(curRow + i));
           }
       }

}